Modify elements in arrays stored in cells at specified rows/columns
Ältere Kommentare anzeigen
Hi, I have a 2d cell array, where each cell contains a 1x2 double,
E.g. X = { [1,0], [1,0], [1,0], [1,0]; [1,0], [1,0], [1,0], [1,0] };
I want to assign the value 1 to the second element in each cell at row r=2, columns c=1:2. Because my actual data is large I want to do this without a for loop. In concept something like:
cellfun( @(c) (X{r,c}(2) = 1), 1:2 );
Thanks in advance
Akzeptierte Antwort
Weitere Antworten (1)
Your cells do not contain arrays with two rows. Look
X = { [1,0], [1,0], [1,0], [1,0]; [1,0], [1,0], [1,0], [1,0] }
Your cells contain a 1-row row vector with 2 columns.
But let's say you did have two ross in the arrays in the cells. I think the best way is to use a for loop:
X = { randi(9, 4, 3), randi(9, 4, 3), randi(9, 4, 3), randi(9, 4, 3);
randi(9, 4, 3), randi(9, 4, 3), randi(9, 4, 3), randi(9, 4, 3)}
% Show the starting values:
celldisp(X)
for k = 1 : numel(X)
% Get cell contents.
thisCellContents = X{k};
% Change it.
thisCellContents(2, 1:2) = [1, 2];
% Put it back into the cell.
X{k} = thisCellContents;
end
% See the result:
celldisp(X)
See? the first and second columns of the second row of each array get changed to 1 and 2 respectively.
Now I know you didn't want a for loop, probably for speed and efficiency, but let's face it - you threw away all possibility of getting speed and efficiency when you decided to use a cell array in the first place.
And it's a myth that cell arrays are horribly slow. Many years ago they've been speeded up a great deal. How many elements are in your cell array anyway? Hundred of millions or billions? For a few million I doubt you'd notice any difference. Any slowness would be caused not by the for loop but by your decision to use a cell array. Look, here is 10 million for loop iterations where it basically does nothing but iterate the for loop:
tic
for k = 1 : 1e7
;
end
toc
Elapsed time is 0.010463 seconds.
How many iterations would you do? See? The for loop alone is not the problem. Takes only a hundredth of a second. It's the data structure and what operations you do that is what eats up the time, not the for loop.
Kategorien
Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!