How can I add element in cell array?

12 ビュー (過去 30 日間)
Muhammad Usama
Muhammad Usama 2018 年 12 月 31 日
回答済み: TADA 2018 年 12 月 31 日
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.

採用された回答

TADA
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 件)

カテゴリ

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