Write a for loop that goes through each row of Matrix
75 views (last 30 days)
Show older comments
Victor Li
on 22 Jan 2021
Edited: Walter Roberson
on 22 Jan 2021
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
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.
Accepted Answer
Walter Roberson
on 22 Jan 2021
for i = 1:size(Z,1)
and refer to Z(i,1) and Z(i,2)
2 Comments
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
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!