Counting rows in excel (new to matlab)

8 views (last 30 days)
so this is my problem i have columns with names and a bunch of "1s" under each column I want to creat a loop that basically converts the table into a matrix and counts the number of "1s" per column and lists that total amount under each name. I cant use sum() or array2table function. i want to learn to create a loop. This is what i was given, it works but i dont want to use sum(data) or array2table
[data,varnames]=xlsread('myfilename.xlsx')
sumdata=sum(data);
T=array2table(sum(data),'VariableNames',varnames)
Name1, Name2, Name3 .......(etc)
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1 1
1 1
1 1
1 1
1 1
1 1
1
1
1
1
1

Accepted Answer

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi on 30 Oct 2019
Hey Aris!
If you necessarily must use a loop (which isn’t optimal though) in your code, consider this block –
data = readmatrix('test.xlsx'); % Import your Excel sheet (‘xlsread’ isn’t recommended)
outVal = zeros(1,size(data,2)); % Matrix to hold your output values
for i=1:size(data,2)
for j=1:size(data,1)
if data(j,i) == 1
outVal(i) = outVal(i) + 1; % Increase the count
end
end
end
The number of 1’s are registered in the variable outVal. You can read more about the function readmatrix here.
Alternatively, if you need the titles ‘Name1’, ‘Name2’, etc. displayed above the counts, consider using a cell array instead. In this case, use readtable command to import the data from the Excel sheet, and then use this field to extract your headings -
data.Properties.VariableNames
Hope this helps!

More Answers (0)

Community Treasure Hunt

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

Start Hunting!