Iterate through rows of excel file and compare values

3 views (last 30 days)
I have a function in MATLAB that reads in columns from an Excel spreadsheet called filename. I want to count the number of times that the column ACC contains 0, and the column participantresponse contains "no tap", and call this EO. Then I want to count the number of times the column ACC contains 0 and the column participantresponse contains "tapped screen", and call this EC. These variables should come out to be close to 50, but the result is 0 every time. Is there something wrong with my loop?
I tried just indexing with one value, like ACC(row), and like ACC(row, 1), but neither of these work.
ACC = xlsread(filename,'K:K');
participantresponse = xlsread(filename,'I:I');
EC = 0;
EO = 0;
row = 1;
x = size(participantresponse);
while (row <= x(1))
if (ACC(row, 1) == 0) && (participantresponse(row, 1) == 'no tap')
EO = EO + 1;
elseif (ACC(row, 1) == 0) && (participantresponse(row, 1) == 'tapped screen')
EC = EC + 1;
end
row = row +1;
end

Answers (1)

Cam Salzberger
Cam Salzberger on 6 Nov 2017
Hello Drew,
There are several issues with the code that I see:
The first output argument from xlread is numeric data. If the column contains text data, you can only get that as the second output argument from xlsread:
[~, participantresponse] = xlsread(...
At this point, I'd recommend examining the variables ACC and participantresponse to ensure that they contain the expected data. This will help catch the issue early if something else is messed up (like numbers stored as text, or accidentally getting the wrong column, or using basic mode instead of full because you are on a non-Windows machine).
Text data extracted by xlsread will be stored in a cell array of character vectors. So you'll want to index with {} rather than ().
...participantresponse{row}...
Don't use == to compare character vectors. If you do, it will produce a logical array the same length as the two inputs, or error if they are different (non-scalar) lengths. Instead, use strcmp.
No need to use size to get all dimensions, then only use one of them. You can just do:
nRows = size(participantresponse, 1);
There's really no need for the loop at all. If you vectorize your code, you can do the whole comparison in two lines:
EO = nnz(ACC == 0 & strcmp(participantresponse, 'no tap'));
Note that the & without the short-circuit operator is used to compare each element of the array. Also note that strcmp works on cell arrays of character vectors as well. I'll leave it to you to do the calculation for EC too.
-Cam

Community Treasure Hunt

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

Start Hunting!