필터 지우기
필터 지우기

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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by