Write a for loop that goes through each row of Matrix

75 views (last 30 days)
Hi
I'm kinda stuck here, how to write a for-loop that goes through each row of matrix Z and does the following:
  • If the second column value is 1, display the first column value;
  • if the second column value is 2, display the negative of the first column value;
  • if it is 3 then times the first column by 2
Here's what I currently have:
for i = 1:size(Z,1)
if Z(i,2)==1
value1 = Z(i,1)
disp(value1)
else Z(i,2)==2
value2 = Z(i,1)<0
disp(value2)
end
if Z(i,2)==3
value3 = Z(i,1)*5
disp(value3)
end
end
The Z can be any matrix, e.g.,
Z = [27 3;
55 3;
53 2;
24 3;
49 1;
63 1];
  3 Comments
Walter Roberson
Walter Roberson on 22 Jan 2021
Edited: Walter Roberson on 22 Jan 2021
Your current code multiplies the first column by 5 instead of by 2 for the case of 3.
And remember, that for 2, you not expected to output information about whether the first column is negative: you are expected to output the negative of the first column. For example your entry [53 2] should result in -53 being displayed.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 22 Jan 2021
for i = 1:size(Z,1)
and refer to Z(i,1) and Z(i,2)
  2 Comments
Victor Li
Victor Li on 22 Jan 2021
Edited: Victor Li on 22 Jan 2021
thanks, but how would the size function help me index into the 1st and 2nd column values in the matrix? Just updated with the newest code I wrote, is this what your are implying?
Walter Roberson
Walter Roberson on 22 Jan 2021
size(Z,1) gives you the information about the number of rows that are in Z. You will be using for i to loop over the row numbers. At any one point, i will be your current row number.
for i = 1:size(Z,1)
if Z(i,2)==1
value1 = Z(i,1)
disp(value)
elseif Z(i,2)==2 %<--- notice
value2 = Z(i,1)<0
disp(value2)
That part will test whether the first column is less than 0, and will display 1 if it is negative and 0 if it is not negative. But that is not what your assignment asks. For example if the first column is 5 then you need to display -5 and if the first column is -5 then you need to display 5.
There are a number of different ways to calculate the negative of a number. For example, the classical definition is
negative_x = 0 - x

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!