How can I add element in cell array?
조회 수: 9 (최근 30일)
이전 댓글 표시
I have a cell array
A = {[2 3 4 ];
[5 6 7 8];
[9 10 11]}
I want add element "1" in start of every array of the cell after adding some constant to every element of "A". e.g.
% B = {1 1+A}
How can I do this on matlab without destructring my cell A.
댓글 수: 0
채택된 답변
TADA
2018년 12월 31일
This sort of operations is best performed on matrices and not cell arrays
So it's better to transform your cell array into a matrix first. you can resize your arrays filling them with NaN to fit the longest arrays using padarray if you have image processing toolbox:
A = {[2 3 4 ];...
[5 6 7 8];...
[9 10 11]};
% find length of longest vector
maxLength = max(cellfun(@length, A));
% pad all vectors with NaN to fit this length
A = cellfun(@(a) padarray(a, [0, maxLength - length(a)], nan, 'post'), A, 'UniformOutput', false);
% turn into matrix and perform operations
B = [ones(size(A,1),1), cell2mat(A) + 1]
B =
1 3 4 5 NaN
1 6 7 8 9
1 10 11 12 NaN
If you MUST use a cell array at some point for some reason, you can always change it back to a cell array:
% turn back to cell array
A = mat2cell(B, repmat(size(A,2),1,size(A,1)));
% get rid of NaN values
A = cellfun(@(a) a(~isnan(a)), A, 'UniformOutput', false);
% show cell contents
celldisp(A);
A{1} =
1 3 4 5
A{2} =
1 6 7 8 9
A{3} =
1 10 11 12
But if you MUST use a cell array, you are better off with an old school for loop:
A = {[2 3 4 ];...
[5 6 7 8];...
[9 10 11]};
for i = 1:length(A)
A{i} = [1, A{i} + 1];
end
% show cell contents
celldisp(A);
A{1} =
1 3 4 5
A{2} =
1 6 7 8 9
A{3} =
1 10 11 12
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!