MATLAB Answers

Converting a cell array into a matrix of stipulated number of columns and rows

1 view (last 30 days)
Consider I have a cell array containing 4 cells
Each cell containd 'n' elements
Now I want to covert it into an array of size "n*4" where element of each row is take from elements of each cell
If it has tto be more clear for eg: ist row of the matrix contains 4 elements - each element is picked from 1st element of each cell.
I have used the model
for i = 1:numel(W{1})%w is the cell
wid(i,:)=double(cellfun(@(v) v(i),W));
end
But it is taking more time in matlab.So, is there any best and simple solution for this problem which can be simulated in less time?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 12 Dec 2019
Edited: Andrei Bobrov on 12 Dec 2019
Let C - your cell array.
if cells sizes are the same:
out = reshape(cat(2,C{:}),[],4);
if not the same:
out = cell2mat(cellfun(@(x)x(:),C,'un',0));

  0 Comments

Sign in to comment.

More Answers (1)

Sign in to answer this question.

Products


Release

R2019b