MATLAB Answers

Cell2mat not working for unequal length cell data/array

6 views (last 30 days)
I am trying to process and plot the CAN message data in Matlab. To do this I am using the following code to import data from *.asc file into Matlab workspace.
canMsgs = canMessageImport('MsgLog.asc', 'Vector', candb, 'OutputFormat', 'timetable')
(my understanding is this code imports hex data for every row in the log file as cell array (as dec numbers) in the output)
Once the data is been loaded into workspace, I am converting the imported timetable data to table format using the below comand.
canMsgs = timetable2table(canMsgs).
The cell array loaded from CAN data is off different length (depending on the byte size (4,6,8)) and when I use the cell2mat function to split the cell array into individual columns I am getting the following error. I am looping through to do this with the below code
for i = 1:length(canMsgs.Data)
C(i,:) = cell2mat(canMsgs.Data(i));
Below is the error I am seeing
Subscripted assignment dimension mismatch.
Error in CAN_Test (line 23)
C(i,:) = cell2mat(canMsgs.Data(i));
I have attached a screenshot from matlab workspace showing the data size, below is the sample data. Individual line represents single cell array (can be seen in the attached image for reference)
Please help me to fix this issue.
Thanks in advance.


Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 17 Jan 2020
Nmsg = length(canMsgs.Data);
msglen = cellfun(@length, canMsgs.Data);
maxlen = max(msglen);
C = nan(Nmsg, maxlen);
for i = 1:Nmsg
thismsg = canMsgs.Data{i};
C(i,1:length(thismsg)) = thismsg;
This creates C as a numeric matrix in which shorter messages are NaN padded to the length of the longest message. (You have to adopt some convention to mark shorter messages if the messages are not all the same length.)

  1 Comment

Logesh Velusamy
Logesh Velusamy on 20 Jan 2020
This works perfect for me. Thanks a lot for your help.

Sign in to comment.

More Answers (0)

Sign in to answer this question.