how to access cell array data with single for loop

1 回表示 (過去 30 日間)
singh
singh 2015 年 4 月 27 日
回答済み: Thorsten 2015 年 4 月 27 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by