Find Number of values filtered through conditioned for loops

1 Ansicht (letzte 30 Tage)
Tareq Khreim
Tareq Khreim am 28 Sep. 2020
Beantwortet: David Hill am 28 Sep. 2020
I have a for-loop in which I'm generating x & y values and filtering them under conditions to prepare them for another, nested for-loop. I want to know how to get the amount of values left after filtering so I can run the next for-loop for that many iterations. As below, I start with 100 random values and have them filtered by an if statement, so how can I get the count of the filtered values? If I try to fill in a matrix it only fills in values from the last iteration.
filtered_array=[];
for i=1:100
x = rand;
y = rand;
if (abs(x)<=1/2) && (abs(y)<=1/2) % Filtering
filtered_array = [x y] % Maybe populate a matrix?
for i=1:length(filtered_array) % for loop only iterating as few times as it needs
...
end
end
end

Antworten (1)

David Hill
David Hill am 28 Sep. 2020
No loops needed.
x=rand(1,100);
y=rand(1,100);
filtered_array=[x(abs(x)<=.5),y(abs(y)<=.5)];
a=length(filtered_array);%this provides the length

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by