Search code examples
excelmatlabdifferencecell-arrayxlsread

How do I subtract two arrays of cells in Matlab


I am trying to get some variables and numbers out from an Excel table using Matlab.

The variables below named "diffZ_trial1-4" should be calculated by the difference between two columns (between "start" and "finish"). However I get the error:

Undefined operator '-' for input arguments of type" 'cell'.

And I have read somewhere that it could be related to the fact that I get {} output instead of [] and maybe I need to use cell2mat or convert the output somehow. But I must have done that wrongly, as it did not work!

Question: How can I calculate the difference between two columns below?

clear all, close all

[num,txt,raw] = xlsread('test.xlsx');



start = find(strcmp(raw,'HNO'));

finish = find(strcmp(raw,'End Trial: '));

%%% TIMELINE EACH TRIAL

time_trial1 = raw(start(1):finish(1),8);
time_trial2 = raw(start(2):finish(2),8);
time_trial3 = raw(start(3):finish(3),8);
time_trial4 = raw(start(4):finish(4),8);

%%%MOVEMENT EACH TRIAL

diffZ_trial1 = raw(start(1):finish(1),17)-raw(start(1):finish(1),11);
diffZ_trial2 = raw(start(2):finish(2),17)-raw(start(2):finish(2),11);
diffZ_trial3 = raw(start(3):finish(3),17)-raw(start(3):finish(3),11);
diffZ_trial4 = raw(start(4):finish(4),17)-raw(start(4):finish(4),11);

Solution

  • You are right, raw contains data of all types, including text (http://uk.mathworks.com/help/matlab/ref/xlsread.html#outputarg_raw). You should use num, which is a numeric matrix.

    Alternatively, if you have an updated version of Matlab, you can try readtable (https://uk.mathworks.com/help/matlab/ref/readtable.html), which I think is more flexible. It creates a table from an excel file, containing both text and numbers.