Find Number of values filtered through conditioned for loops

1 次查看(过去 30 天)
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

回答(1 个)

David Hill
David Hill 2020-9-28
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by