Vectorization of a for loop

1 visualizzazione (ultimi 30 giorni)
Nicholas Xiao
Nicholas Xiao il 27 Nov 2019
Modificato: Nicholas Xiao il 3 Dic 2019
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.

Risposta accettata

Bhaskar R
Bhaskar R il 27 Nov 2019
Modificato: Bhaskar R il 27 Nov 2019
% 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 Commento
Nicholas Xiao
Nicholas Xiao il 27 Nov 2019
Modificato: Nicholas Xiao il 3 Dic 2019
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!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by