Searching through Matrix with conditional statements

I am trying to run a loop through the second colum of my data to see if it is >200. Once the loop has gone through all the rows of the second column i want the final output "Yield_Count" to give me the total count of materials that are above 200. Please note i want this to be for any size matrix.
for example if 8 of the rows number is greater than 200 in the second column i want the "Yield_Count: output to give 8.
%input data matrix as "Materials"
Materials = [1 170 284 60 307; 2 292 380 69 509; 3 294 397 82 511; 4 237 380 90 818; 5 159 341 55 795; 6 186 360 97 645; 7 203 310 89 379; 8 274 399 75 812; 9 153 288 72 533; 10 157 388 73 351];
MPa = 200 %condition
Yield_Count = 0 %Set value for number of materials whose yield is >200MPa
if Materials(:,2) > MPa; %Condition
Yield_Count (Materials) = Yield_Count + 1 %Add 1 counter for each material that >200MPa
else if Materials(:,2) <200
Yield_Count (Materials) = Yield_Count + 0 %Add 0 counter for each material that is not >200MPa
end
end
disp(Yield_Count) %Diplay the total number of materials that have >200MPa

 Accepted Answer

No loops needed.
Yield_Count=nnz(Materials(:,2)>200);

5 Comments

I am a student and this is for an assignment. This leads onto further questions analysing the data set. for example if it mets one condition does it meet another? what is the function to loop through a specific colum or row to meet a conditional statment? Thank you for your time answering me.
(Materials(:,2)<500&Materials(:,2)>200);%provides logical array of same length as column when the condition is met
(Materials(5:1)==100);%provides logical array of row values that equal 100
Look at documentation on array indexing and logical arrays. One of the strengths of matlab is indexing into arrays.
Thank you for your help. I will look into it now.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!