MATLAB Answers


how to access cell array data with single for loop

Asked by singh on 27 Apr 2015
Latest activity Commented on by DEEPAK PHCSFI17041149 on 29 Nov 2017
two cell array like
A={1,2,3,4,5} %cell array
B={11,12,13,14,15} %cell array
for i=1:length(A)
C %variable
D %variable
in first iteration C take 1 from A and D take 11 from B
second iteration C take 2 from A and D take 12 from B
So on
use only single for loop


Why are these values in cell arrays anyway? Unless you have mixed data types or different sizes, just use a simple numeric array to store those values.
Also note that, depending on what operations you need to perform, the entire loop might be able to be replaced with vectorized code. If you show us what the operations are inside the loop, then we could show you if this can be simplified by vectorization.
i have some problem because actual cell array value is below
6 11
1 9
1 9
6 11

Sign in to comment.

2 Answers

Answer by per isakson
on 27 Apr 2015
Edited by per isakson
on 27 Apr 2015
 Accepted Answer

C = cell( size(A));
D = cell( size(B));
for ii=1:length(A)
C(ii) = A(ii);
D(ii) = B(ii);
Without the loop - vectorized
C = A;
D = B;


Show 1 older comment
Hey Isak, any idea how to do it for saving Variable C as C1, C2, C3 on loops? i mean when A = {1,2,3,4,5} Then C1 = 1, C2 = 2, C3 = 3, C4 = 4, C5= 5?
Thanks for the guidance Isak.

Sign in to comment.

Answer by Michael Haderlein on 27 Apr 2015

You mean like
for cnt=1:length(A)
Actually, there is no need for cell arrays here. In case this is just a simplified example and A and B will be of different kind in your final program, it's fine. Otherwise, I would make A and B just normal double arrays.


Sign in to comment.