how to access cell array data with single for loop

1 次查看(过去 30 天)
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 个评论
Guillaume
Guillaume 2015-4-27
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.

请先登录,再进行评论。

回答(1 个)

Thorsten
Thorsten 2015-4-27
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

类别

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