Write a for loop that goes through each row of Matrix

75 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2021-1-22
编辑:Walter Roberson 2021-1-22
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.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2021-1-22
for i = 1:size(Z,1)
and refer to Z(i,1) and Z(i,2)
  2 个评论
Victor Li
Victor Li 2021-1-22
编辑:Victor Li 2021-1-22
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 2021-1-22
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by