sum logical 1's independently for each column
Show older comments
I've attached a sample data from excel.
how can I create a "for loop" to sum each column and give me print out total for each column.
I also need to compare the "length" of the column to the sum of the logical 1's in that column then print out a pass or fail for each column tested.
example:
1 1 1 1
1 1 1 1
1 1 1 0
1 1 1 1
-----------sum
first column = 4 ==length(column) = pass
fourth column = 3 == lenght(column = fail
Accepted Answer
More Answers (2)
David Hill
on 12 Feb 2022
No loop is needed.
r=readmatrix('logicalDataCount.xlsx');
s=sum(r);
l=s==size(r,1);
10 Comments
Michael Angeles
on 12 Feb 2022
David Hill
on 12 Feb 2022
That is the logical array l.
Image Analyst
on 12 Feb 2022
Edited: Image Analyst
on 12 Feb 2022
l is probably a bad name because it looks too much like l or 1. Let's call it numPasses.
numPasses = sum(r);
allPassed = (numPasses == size(r, 1)); % Or better use DGM's answer with all(r, 1)
% Print out strings for pass or fail.
for k = 1 : length(numPasses)
if allPassed(k)
fprintf('Pass ')
else
fprintf('Fail')
end
end
% Print line feed after it's all done.
fprintf('\n');
Michael Angeles
on 12 Feb 2022
Edited: Michael Angeles
on 12 Feb 2022
Image Analyst
on 12 Feb 2022
Yes.
numPasses = sum(r);
allPassed = (numPasses == size(r, 1)); % Or better use DGM's answer with all(r, 1)
% Print out strings for pass or fail.
% First print out a column meader line.
fprintf('Column 1 Column2 Column3 Column4 \n');
for k = 1 : length(numPasses)
if allPassed(k)
fprintf('Pass ')
else
fprintf('Fail')
end
end
% Print line feed after it's all done.
fprintf('\n');
Michael Angeles
on 12 Feb 2022
David Hill
on 12 Feb 2022
Do you have multiple files to read then?
l=cell(1,numOfFiles);
for k=1:numOfFiles
r=readmatrix(strcat('logicalDataCount',num2str(k),'.xlsx');%I have no idea what all your files are named
s=sum(r);
l{k}=size(r,1);%you will need a cell array since the sizes are different
end
Michael Angeles
on 13 Feb 2022
David Hill
on 13 Feb 2022
The below code is completely flexible (does not depend on the size of r)
s=sum(r);
allPassed = (numPasses == size(r, 1));
You are really not understanding, the logical array above tells you every column that is passed (1) or failed (0). Converting the logical array to 'pass' or 'fail' is trivial.
Michael Angeles
on 13 Feb 2022
Michael Angeles
on 14 Feb 2022
0 votes
Categories
Find more on Categorical Arrays 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!