Cell2mat - creating a matrix from mismatched cell sizes

7 ビュー (過去 30 日間)
Karen Hornsby
Karen Hornsby 2013 年 1 月 16 日
回答済み: Samira Abedi 2019 年 1 月 2 日
Does anyone know how to create a matrix from a cell array where some of the cells have different lengths? Basically my instrument got interrupted when writing it's output file and finished halfway through a line. I don't want to discard the file as it's 99% complete. Is there another command which selectively converts a given sample size of a cell?
  4 件のコメント
Matt J
Matt J 2013 年 1 月 17 日
If your data is initially acquired as a file, how did it get into cell array form? Why would you import the file to a cell array if you ultimately want it to be a vector?
Samira Abedi
Samira Abedi 2019 年 1 月 2 日
I get the following error when applying the above code:
Attempt to grow array along ambiguous dimension.

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2013 年 1 月 17 日
No, you cannot do that. So what you do instead is figure out where the smaller lines are and pad those rows with enough NaN to match the size of the other rows. Then you can cell2mat()
  3 件のコメント
Walter Roberson
Walter Roberson 2013 年 1 月 17 日
prevlen = sum(cellfun(@length, C(end-1,:)));
lastlen = sum(cellfun(@length, C(end,:))));
C{end,end} = [C{end,end}, NaN(1,prevlen - lastlen)];
mat2cell(C)
Joel Torby
Joel Torby 2018 年 5 月 22 日
C=yourCellArrayWithDifferentSizes;
maxLengthCell=max(cellfun('size',C,2)); %finding the longest vector in the cell array
for i=1:length(C)
for j=cellfun('size',C(i),2)+1:maxLengthCell
C{i}(j)=0; %zeropad the elements in each cell array with a length shorter than the maxlength
end
end
A=cell2mat(C); %A is your matrix

サインインしてコメントする。

その他の回答 (2 件)

Jan
Jan 2013 年 1 月 17 日
What do you want as output for:
C = {[], 1, 1:2}
?
  2 件のコメント
Karen Hornsby
Karen Hornsby 2013 年 1 月 17 日
Do you mean that the code above removes row 1 of column 1&2?
Jan
Jan 2013 年 1 月 17 日
No, "C" is a cell, which contains vectors of different length. Simply copy it to the command window and run it. It is exactly what you have explained by:
... a cell array where some of the cells have different lengths?
Now you ask us for creating a matrix from such an input. So how should the output look like in this case?

サインインしてコメントする。


Samira Abedi
Samira Abedi 2019 年 1 月 2 日
I get the following error when I apply the suggested method:
Attempt to grow array along ambiguous dimension.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by