MATLAB Answers

How can I use while loops to determine if an element is larger than the element below it and store the results in a vector with 1 representing true and 0 representing false?

41 ビュー (過去 30 日間)
Yen Tien Yap
Yen Tien Yap 2021 年 3 月 26 日
編集済み: John D'Errico 2021 年 3 月 26 日
I coded for my while loop but I can't get the final answer and the error showed that 'Array indices must be positive integers or logical values.' Can someone help me with this? Thank you so much!!
A=randi([0 9],1,randi([100 300]))'
n=numel(A)-1
B=zeros(n,1)
while i<=n
if A(i)>A(i+1)
B(i,1)=true
else
B(i,1)=false
end
i=i+1
end
  1 件のコメント
Stephen Cobeldick
Stephen Cobeldick 2021 年 3 月 26 日
You are using i as an index. What is the value of i ? (hint: the square root of -1)

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

採用された回答

Matt J
Matt J 2021 年 3 月 26 日
A=randi([0 9],1,10)';
n=numel(A)-1;
B=zeros(n,1);
i=1;
while i<=n
if A(i)>A(i+1)
B(i,1)=true;
else
B(i,1)=false;
end
i=i+1;
end
A.',B.'
ans = 1×10
0 2 1 8 0 9 4 2 6 2
ans = 1×9
0 1 0 1 0 1 1 0 1

その他の回答 (1 件)

John D'Errico
John D'Errico 2021 年 3 月 26 日
編集済み: John D'Errico 2021 年 3 月 26 日
"While" this does not answer your question, I would not use a while loop at all. Learn to use MATLAB as it is designed.
A = randn(1,8) % some random numbers
A = 1×8
-0.2087 0.3007 -0.3599 -0.0566 0.4045 -3.0370 -0.3818 0.8694
B = [false,diff(A)>0] % A vector of the same length as A, true when A(i+1) > A(i)
B = 1×8 logical array
0 1 0 1 1 0 1 1
B is the same length as A. Note that A(1) will never be greater than the preceding element, since there is no preceding element.
Could you use a while loop? Yes. A for loop would make more sense as a loop here, since you want to test EVERY pair of elements.
B = false(size(A)); % preallocate B
for ind = 2:numel(A)
B(ind) = A(ind) > A(ind-1);
end
B
B = 1×8 logical array
0 1 0 1 1 0 1 1
Same result as the single statement, but a loop.
CAN you use a while loop? Well, yes. Learn when to use one type of loop over another when you REALLY need to use a loop. A while loop is good when you don't know how often the loop will run. A for loop is right when you have a known, fixed number of iterations.

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by