I am doing a project in matlab,first time using it,and our prof sent us this code,can someone explain to me what thats doing? Thank you.

5 views (last 30 days)
function [Vout, t] = stackoutput(lb, ub, cost1)
n= size(cost1);
n1= n(1);
n1b= n(2);
Vout= zeros(n1,n1b);
t=1;
for i=1:n1
if(cost1(i,1)>= lb && cost1(i,1)<= ub)
Vout(t,:)=cost1(i,:);
t=t+1;
end
end
t= t-1;
end

Answers (1)

DGM
DGM on 28 Oct 2021
Edited: DGM on 28 Oct 2021
Without context, I doubt anyone can tell you anything more than a literal reading of the code. This is why documentation (a synopsis or at least a single comment) is important. Whoever gave you a bunch of undescribed code is the person to ask.
Buuut I guess nobody likes climbing that hill. Let's add some comments to this thing.
function [Vout, t] = stackoutput(lb, ub, cost1)
% [Vout t] = stackedoutput(lowerbound,upperbound,cost)
% This function does a thing that is so unimportant that
% it's not even worth writing a single word in description.
%
% LOWERBOUND is a numeric scalar
% UPPERBOUND is a numeric scalar
% COST is a numeric matrix (2D)
%
% VOUT is a numeric matrix containing the rows from COST where
% the first column falls between LOWERBOUND and UPPERBOUND
% T is a numeric scalar representing the number of valid rows in VOUT
n= size(cost1);
n1= n(1);
n1b= n(2);
Vout= zeros(n1,n1b); % initialize Vout to be same size as cost1
t=1; % output row index starts at one
for i=1:n1 % step row by row
% if first element of this row is within bounds
if(cost1(i,1)>= lb && cost1(i,1)<= ub)
% then cram that row into the output array on row t
Vout(t,:)=cost1(i,:);
% and increment the output row index
t=t+1;
end
end
% since this index is used as a counter and we started at 1 instead of zero
% we have to subtract one to have a correct count of valid rows
t= t-1;
end
This whole mess with loops can be replaced:
function [Vout, numvalidlines] = stackedthing2(lowerbound,upperbound,cost)
% synopsis goes here
[h w] = size(cost);
Vout = zeros(h,w);
inbound = (cost(:,1) >= lowerbound) & (cost(:,1)<= upperbound);
numvalidlines = nnz(inbound);
Vout(1:numvalidlines,:) = cost(inbound,:);
end
Since there's zero context provided, it's not clear whether the output array is ideally supposed to have a bunch of extra empty rows. If not, the answer can be simplified further yet.
function [Vout, numvalidlines] = stackedthing3(lowerbound,upperbound,cost)
% synopsis goes here
% same thing, but without extra empty rows
inbound = (cost(:,1) >= lowerbound) & (cost(:,1)<= upperbound);
Vout = cost(inbound,:);
numvalidlines = size(Vout,1);
end

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!