필터 지우기
필터 지우기

How to Convert Cell Array to Multiple Variables All At Once?

조회 수: 10 (최근 30일)
John Gow
John Gow 2018년 9월 26일
편집: Stephen23 2018년 9월 26일
I have a 1x8 cell array, where each unit is a 3X3 'matrix'. I can use:
a(1) = mydata{:,1};
a(2) = mydata{:,2};
to get each subsequent matrix assigned to an 'a(n)' variable where n is just a consecutive number.
How do I use for loops or some other command to get all individual cell array units assigned each a variable a(n) all at once?
-in instances where the cell array may be 1:9000000000000. I would not want to assign them manually each time.
Thank you.
  댓글 수: 1
Stephen23
Stephen23 2018년 9월 26일
편집: Stephen23 2018년 9월 26일
"...to get each subsequent matrix assigned to an 'a(n)' variable where n is just a consecutive number."
What you describe is either basic indexing of one variable a, or dynamically named variables using sequential numbered names:
  1. Using one variable is trivially simple and could be quite efficient, see the answers below. Note that because your data is equally accessible from within the cell array this step might be superfluous.
  2. Dynamically names variables are one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. The MATLAB documentation specifically advises to avoid doing this. Read this to know why:

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

답변 (2개)

KSSV
KSSV 2018년 9월 26일
C = cell(1,8) ;
for i = 1:8
C{i} = rand(3) ;
end
% With loop
A = zeros(3,3,8) ;
for i = 1:8
A(:,:,i) = C{i} ;
end
% With out loop
CC = cell2mat(C) ;
B = reshape(CC,3,3,[]) ;

Stephen23
Stephen23 2018년 9월 26일
편집: Stephen23 2018년 9월 26일
No loop or cell2mat required:
B = cat(3,a{:})
each slice/page is trivially accessible using efficient indexing:
B(:,:,1)
B(:,:,2)
...
Read more about the syntax I used:

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by