I'm working on a code that requires me to replace the values in an empty matrix with new ones. I'm trying to do this using a while loop but can't seem to get it right can anyone provide some insight as to how I should continue? I was thinking something along the lines of this:
M=zeroes(5)
while M 'contains a zero'
x=randi(5)
Y=randi(5)
M(x,y)='Replavement Value Function'
end
This issue I'm having is I don't understand how to write the while loop such that it will continuously perform this operation until M no longer contains a zero.

 採用された回答

Guillaume
Guillaume 2019 年 1 月 10 日

1 投票

Note: an empty matrix (a matrix whose any dimension is of size 0) and a matrix filled with 0s are two completely different things.
Prior to R2018b, use
while any(M(:) == 0)
to check if any element of M is equal to 0. In R2018b, you can use
while any(M == 0, 'all')
to do the same

3 件のコメント

William Diaz
William Diaz 2019 年 1 月 10 日
Thanks this is what I was looking for! Quick follow up is their a way to track the number of times it has to perform the loop before all the values are replaced?
Guillaume
Guillaume 2019 年 1 月 10 日
Use a counter incremented inside the loop:
counter = 0;
while any(M == 0, 'all')
counter = counter+1;
%...
end
William Diaz
William Diaz 2019 年 1 月 10 日
Perfect thank you

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by