MATLAB Answers

running matrix in a loop to produce another matrix

4 views (last 30 days)
JL
JL on 22 Aug 2019
Commented: JL on 22 Aug 2019
Hi everyone, I have z
z = [1 1 0 0;
1 0 1 0;
1 0 0 1;
0 1 1 0;
0 1 0 1;
0 0 1 1;]
each of z's row are states that I want my code to go through one by one (from 1 1 0 0 to 0 0 1 1) , and after each state is run, it produces w. after running all the 6 states from z,
w = [a;
a;
a;
a;
a;
a;];
Is there a code where I can run each state of z in a loop, and produces w?

  2 Comments

JL
JL on 22 Aug 2019
"a" is calculated number. Meaning, for each time it loop, "a" is generated until the loop finishes.

Sign in to comment.

Accepted Answer

Ted Shultz
Ted Shultz on 22 Aug 2019
This code will loop over each row of Z and put the results into w. I'm not sure what you want to do with each row.
z = [1 1 0 0;
1 0 1 0;
1 0 0 1;
0 1 1 0;
0 1 0 1;
0 0 1 1;]
numRows = size(z,1); % counts the number of rows
w = nan(numRows,1); % preallocate w;
for ii = 1:numRows
thisRow = z(ii,:);
% do something here to get a?
a=sum(thisRow);
w(ii) = a;
end

  3 Comments

JL
JL on 22 Aug 2019
Thanks for this! What if I change my z to
z = [1 2;
1 3;
1 4;
2 4;
1 6;];
and each time before it loop, first loop,
z = [
1 3;
1 4;
2 4;
1 6;]
and then for the second loop,
z = [1 2;
1 4;
2 4;
1 6;];
and so on instead of the initial z

Sign in to comment.

More Answers (0)

Sign in to answer this question.