Can anyone help? I cannot figure out how to use a for loop to check elements in part of a matrix.

1 回表示 (過去 30 日間)
Create a 5x4 matrix of random integers between -10 and 10 with the randi function. Write a for loop that will check each element in column 1 of the matrix. If that element is less than 0, change every element in that row to NaN.
I can make the actual matrix, but after that I don't know what comes next.
r=randi([-10,10],5,4)

採用された回答

Stephen23
Stephen23 2019 年 10 月 30 日
編集済み: Stephen23 2019 年 10 月 30 日
"I can make the actual matrix, but after that I don't know what comes next."
Your assignment tells you exactly what you need to do. Fill in the ??? yourself:
for k = 1:size(???) % loop over all row indices
if r(k,1)<??? % check if first column value is <0
r(k,:)=???; % change entire row to NaN
end
end
  2 件のコメント
Samantha Tomkowich
Samantha Tomkowich 2019 年 10 月 30 日
Thank you so much! I was doing well with matlab until I got to for loops, now I feel like a bit of an idiot. Thank you for your help!!

サインインしてコメントする。

その他の回答 (2 件)

Bhaskar R
Bhaskar R 2019 年 10 月 30 日
編集済み: Bhaskar R 2019 年 10 月 30 日
No need of for loop
r=randi([-10,10],5,4);
if any(r(:,1)<0)
r(1,:) = nan;
end
  2 件のコメント
Stephen23
Stephen23 2019 年 10 月 30 日
The question states that "If that element is less than 0, change every element in that row to NaN", but this code always changes the first row to NaN, not the row/s where the negative values were found in the first column.
It is not clear how if is supposed to provide the requested behavior.
Bhaskar R
Bhaskar R 2019 年 10 月 31 日
編集済み: Bhaskar R 2019 年 10 月 31 日
I am sorry, I misunderstood the question. I thought like there is to change row with respect to given column number.

サインインしてコメントする。


Samantha Tomkowich
Samantha Tomkowich 2019 年 10 月 30 日
Thank you! That got me exactly what I was looking for answer wise, unfortunately the assignment needs me to use a for loop to get the same answer. But thank you!
  4 件のコメント
Samantha Tomkowich
Samantha Tomkowich 2019 年 10 月 30 日
how would I consider more than one row?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by