Filter löschen
Filter löschen

How can I add element in cell array?

9 Ansichten (letzte 30 Tage)
Muhammad Usama
Muhammad Usama am 31 Dez. 2018
Beantwortet: TADA am 31 Dez. 2018
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.

Akzeptierte Antwort

TADA
TADA am 31 Dez. 2018
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

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by