How to only select the last x number of columns when trying to concatenating a matrix using a for loop

30 ビュー (過去 30 日間)
Hello all,
I have a cell of dimensions 1x36, for which 23 of the 36 elements in the cell have dimensions 22 x 91000. The remaining elements in the cell have dimensions 22 x 85000. I am trying to convert this 1x36 cell into a 3D matrix of dimensions 22 x 31000 x 36, where upon the number 31000 corresponds to the last 31000 elements of the 91000 (or 85000) elements of any particular coloumn for any particular cell element.
I tried using the code:
3D_Matrix = cell2mat(My_Cell_Array)
however, I got an error because you cannot concatenate coloumns of unequal length together to create a matrix. I then tried using a for loop structured like this:
for P = 1:22
for K = (Don't know how to code this???)
for J = 1:36
3D_Matrix (:,:,J) = cell2mat(My_Cell_Array(P,K,J));
end
end
end
However, I do not know how to tell matlabe to only take the last 31000 elements of each coloumn of each cell when creating the 3D matrix using the for loops. Could anyone give me an idea on how to properly code this?
Thanks in advanced.

採用された回答

Adam Danz
Adam Danz 2019 年 11 月 4 日
編集済み: Adam Danz 2019 年 11 月 4 日
"I do not know how to tell matlab to only take the last 31000 elements of each coloumn of each cell"
To take the last n columns of a matrix
m(:, end-n+1:end)
To do that for each element of a cell, you can put that line within cellfun().
This demo below achieves what you're looking for (loops not needed). The first line creates a fake dataset that matches your description. array3D is your 3D array. .
% Create fake data
c = [repmat({rand(22,91000)},1,23), repmat({rand(22,85000)},1,13)];
% Extract the last 31000 columns of each cell element
nCol = 31000;
ctrim = cellfun(@(x)x(:, end-nCol+1:end),c,'UniformOutput',false);
% Combine into 3D array
array2D = cell2mat(ctrim);
array3D = reshape(array2D,size(array2D,1),nCol,numel(ctrim));
  2 件のコメント
Brittny Freeman
Brittny Freeman 2019 年 11 月 4 日
Thank you so much for your help, this was exactly what I was looking for, and no for loops necessary!
Thanks again.
Adam Danz
Adam Danz 2019 年 11 月 4 日
Glad I could help!
Check out cellfun() which is the key to avoiding loops in this answer.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by