Vectorization of a for loop

조회 수: 2 (최근 30일)
Nicholas Xiao
Nicholas Xiao 2019년 11월 27일
편집: Nicholas Xiao 2019년 12월 3일
Hi, I am currently having difficulty with vectorizing a for loop. The purpose of the the loop is to iterate through column vector A and output 1 to empty column vector B if the element in A is greater than some scalar, and 0 otherwise. So far I have:
count = 1;
for len = 2:length(filteredArray) + 1
if filteredArray(count) > inputScalar
tempVector(count) = 1;
count = count + 1;
elseif filteredArray(count) <= inputScalar
tempVector(count) = 0;
count = count + 1;
end
end
This works fine, but I have no idea how to vectorize it for better efficiency. I thought about
x = filteredArray(1):1:length(filteredArray) + 1;
tempVector(x) = (filteredArray(x) > inputScalar);
But I don't know how to work in the other condition and the outputs into a new vector. Help would be appreciated and thank you.

채택된 답변

Bhaskar R
Bhaskar R 2019년 11월 27일
편집: Bhaskar R 2019년 11월 27일
% assuming fake data
filteredArray = [8 3 5 6 10 5 10 4 8 7];
inputScalar = 5;
% then apply
tempVector = filteredArray > inputScalar; % this do your requirement
For more info on Array Comparison with Relational Operators read help
  댓글 수: 1
Nicholas Xiao
Nicholas Xiao 2019년 11월 27일
편집: Nicholas Xiao 2019년 12월 3일
I understand that part, but how would I get it to also write 1 or 0 to tempVector based on whether or not filteredArray > inputScalar?
Edit: It works out automatically, thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by