From cell array to matrix

조회 수: 3 (최근 30일)
Lev Mihailov
Lev Mihailov 2019년 7월 25일
댓글: Andrei Bobrov 2019년 7월 25일
Hello! I have cell arrays, help me deal with the loop.
for i = 1:length(Animal)-1
Y=[X{i}];
end
data looks like this % X{1}=[0] X{2}=[0 1.2 1.4 1.6] X{3}=[0] X{4}=[0 1.3 1.5 1.6]....
My task is to create a 4x800 matrix, where if zero is the column [0 0 0 0], and the values ​​will be in the column

채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 7월 25일
Y = cell2mat(cellfun(@(x)[x(:);zeros(4-numel(x),1)],X,'un',0));
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2019년 7월 25일
Hi Lev!
Please attach your data X as mat-file.
Andrei Bobrov
Andrei Bobrov 2019년 7월 25일
Variant:
n = cellfun(@(x)numel(x(:)),X);
m = max(n);
k = numel(X);
Y = zeros(m,k);
for ii = 1:k
Y(1:n(ii),ii) = x{ii};
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Felix Albrecht
Felix Albrecht 2019년 7월 25일
Try preallocating with zeros:
Y = zeros(4,800);
% Assuming that length(Animal)-1 = 800
for i = 1:length(Animal)-1
Y(:,i) = X{i};
end
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2019년 7월 25일
+1
Lev Mihailov
Lev Mihailov 2019년 7월 25일
편집: Lev Mihailov 2019년 7월 25일
Y = zeros(4,800);
% Assuming that length(Animal)-1 = 800 length(Animal)=801
for i = 1:length(Animal)-1
Y(:,i) = X{i}; % X{i} 1x800
end
Index exceeds matrix dimensions.
Error in Max_int2407edt (line 9408)
what could be wrong?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by