MATLAB Answers

Hi, i have a 87 * 1 cell array as shown below. how to convert it into a 87 X 11 matrix? Thanks!

1 view (last 30 days)
Ivy Shen
Ivy Shen on 28 Aug 2018
Commented: Ivy Shen on 31 Aug 2018

  0 Comments

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 28 Aug 2018
There might be a more compact way, but this works:
% Create sample data charaxcter array
charArray = sprintf('1013.0 3 14.6 13.0 9.37 0 0 286.7 312.9 288.3');
charArray = repmat(charArray, [87, 1])
% Convert to numbers.
rows = size(charArray, 1)
for row = 1 : size(charArray, 1)
thisRow = sscanf(charArray(1,:), '%f')
if row == 1
columns = size(thisRow, 1);
numbers = zeros(rows, columns)
end
numbers(row, :) = thisRow'
end

More Answers (1)

Geoff Hayes
Geoff Hayes on 28 Aug 2018
Ivy - assuming that your elements of the cell array are strings you could try
cell2mat(cellfun(@(x)str2num(x), data, 'UniformOutput',false))
where data is your cell array. For example,
data = {'1.1 1.2 1.3' ; '3.1 3.3 3.5'};
dataAsMatrix = cell2mat(cellfun(@(x)str2num(x), data, 'UniformOutput',false));
returns a 2x3 array
1.1000 1.2000 1.3000
3.1000 3.3000 3.5000

  2 Comments

Ivy Shen
Ivy Shen on 28 Aug 2018
Thank you Geoff, but there is another error which states that the input #3 expected to be a cell array, was char instead. What should I do to solve this problem?
Geoff Hayes
Geoff Hayes on 28 Aug 2018
Ivy - so perhaps your array really isn't a cell array but is an array of characters instead? If this is true, then the above code I posted will not work since it assumes that the data you are passing in is a cell array. Can you show your code and perhaps attach a small sample of your data?

Sign in to comment.

Sign in to answer this question.