MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。


Using a While loop to determine number greater than a constant

Lena Weisman さんによって質問されました 2019 年 3 月 11 日
最新アクティビティ Rik
さんによって コメントされました 2019 年 3 月 14 日
I have to consider the following matrix of values. X = [15, 53, 27, 32, 25, 23] and use a while loop to determine the number of values greater than 24. (Use a counter).
This is what I have any help would be greatly appreciated!
clear all;
while X>24
fprintf('Values over 24 in the Matrix are: %i \n',Y)

  3 件のコメント

2019 年 3 月 11 日
Can you explain your reasoning why you wrote your code like this? It helps to think step by step what happens in these lines.
Also, do you really need to use a while loop? You can easily solve this without a loop.
As a last remark: never use clear all. Use functions to keep your workspace clean, and/or use clear variables to clean up variables.
Thanks! I have to write the code like this per a professors request which is also the reason for the while loop. The problem is that I am getting an output of 0 when the answer should be 4.
2019 年 3 月 14 日
Did my suggestions help you solve the issue? If not, feel free to comment with any further questions.

サインイン to comment.

1 件の回答

回答者: Rik
2019 年 3 月 11 日

I'm a bit hesitant to provide you with a complete working solution, since you mention it is homework. I will give you some advice in addition to my first comment:
Use a counter to check if you still have to check the next value in your vector (in your while condition). Use a second counter to keep track of values greater than your threshold.
What while X>24 does is to check the entire vector X against 24, and then that logical vector is used as the criterion. I can never remember what Matlab does in these cases, nor do I need to. You should avoid using an entire vector as a test. Always use the any or all functions to convert them to a scalar. You will (almost) never mean to use a vector as a conditional.
In your case, the while loop immediately exits, which results in the output answer being 0. If Matlab would enter the loop, it would continue looping, since the criterion is not affected by the loop contents.

  0 件のコメント

サインイン to comment.

Translated by