Can anyone help? I cannot figure out how to use a for loop to check elements in part of a matrix.
2 次查看(过去 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)
0 个评论
采纳的回答
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 个)
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
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.
另请参阅
类别
在 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!