how to access cell array data with single for loop
    1 visualización (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
 A={1;{2,3};{4,5}} %cell array
 B={11,12);{13,14};15}   %cell array
 C = cell( size(A));
 D = cell( size(B));
 for ii=1:length(A)
     C(ii) = A(ii);
     D(ii) = B(ii);
 end
i wish to use only one for loop and i get output from this code is
 when iteration ii =1 then 
C=1
D=11
 iteartion ii=2 then 
C=2
D=12
 iteratioin ii=3 then
C=3
D=13
 iteration ii=4 then
C=4
D=14
 iteartion ii=5
C=5
D=15
i need only one for loop whole process
1 comentario
  Guillaume
      
      
 el 27 de Abr. de 2015
				Why do you want to use a loop in the first place? Assuming A and B are the same size, your code is the same as
C = A;
D = B;
If A and B are not the same size, in particular if the largest dimension of A is greater than the number of elements in B, then your code will error, since you use the A dimension to access the B dimension.
Finally, I wouldn't use length. I would use numel for vectors.
Respuestas (1)
  Thorsten
      
      
 el 27 de Abr. de 2015
        C = flatten(A);
D = flatten(B);
using my function
function [y, me] = flatten(x)
%FLATTEN Flatten numeric data (ND matrices or arbitrarily nested cells)
%
%   [Y, ME] = FLATTEN(X)
%
%Sample usage:
%  A={1; {2,3}; {4,5}; {6,{7,8}}}
%  flatten(A)
%
%   Thorsten.Hansen@psychol.uni-giessen.de  2015-04-27
if ~iscell(x)
  y = x(:);
else
  y = [];
  for i = 1:numel(x)
    try
      xi = cell2mat(x{i});
    catch me
      xi = flatten(x{i});
    end
    y(end+1:end+numel(xi)) = xi;
  end
end
0 comentarios
Ver también
Categorías
				Más información sobre Matrices and Arrays en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!