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
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
2021-1-22
for i = 1:size(Z,1)
and refer to Z(i,1) and Z(i,2)
2 个评论
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!