cell to double with mismatched dimensions

조회 수: 1 (최근 30일)
Jonathan Soucy
Jonathan Soucy 2016년 8월 29일
댓글: Jonathan Soucy 2016년 8월 29일
Input:
a = cell(3,1);
a{1,1} = [1 2 3];
a{2,1} = [1 2 3 4];
a{3,1} = [1 2 3 4 5];
Desired output:
b = [[1 2 3 0 0];[1 2 3 4 0];[1 2 3 4 5]];
What would be the best way to get this output from this input?

채택된 답변

Geoff Hayes
Geoff Hayes 2016년 8월 29일
편집: Geoff Hayes 2016년 8월 29일
Jonathan - one way would be to use cellfun to apply a function to each element of your cell array padding each with zeros so that all arrays are of the same length. For example, we can get the maximum length as
maxLength = max(cellfun(@(x)length(x),a));
We would then use cellfun again to pad the arrays with zeros using repmat (which just repeats a matrix) as
aPadded = cellfun(@(x)[x repmat(0,1, maxLength - length(x))],a,'UniformOutput',false);
Finally, use cell2mat to convert your cell array into a matrix as
b = cell2mat(aPadded);
Try the above and see what happens!
  댓글 수: 1
Jonathan Soucy
Jonathan Soucy 2016년 8월 29일
Hi Geoff, that worked very well. Thank you! I also came up with this solution which is actually very similar to what you came up with
a_max = max(cellfun(@length,a));
b = zeros(length(a),a_max);
for m = 1:length(a)
b(m,:) = [a{m,1} zeros(1,(a_max-length(a{m,1})))];
end
I'm not sure which option is best, but I guess it is good to have options

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by