Perform action for Cell Array without using for loop

13 次查看(过去 30 天)
I have a cell array of size (100,2000) and I want to take the last row of every cell and add it to a new cell array. I'm doing this to reduce the memory requirement of the cell array. Right now I am using a for loop to loop through the cells in the array, but this being matlab there probably is a better and faster way of doing this. Anyone have an idea how to perform this calculation without using a for loop?
The code below shows what I am talking about. r is 200, c is 2000 and the if statement checks if the cell is empty or not. If it is empty I don't want to do anything, if it contains data I want the last row of the cell to be saved to a new cell array.
Is there a faster way of doing this?
for ma = 1:r
for alti = 1:c
if isempty(itteration_record{ma,alti}) == 0
input_Config.itteration_record{ma,alti} = itteration_record{ma,alti}(end,:);
end
end
end

采纳的回答

Salman Ahmed
Salman Ahmed 2021-8-4
Hi Joris,
From my understanding, you would like to extract the non-empty cells in a cell array. And then you want to extract the last rows of the non-empty cells and assign to a new cell array. Here is an example of cellfun to assist you in performing the same without using for loops.
% Let us assume an empty cell A of size (3,3)
A = cell(3,3);
% Use cellfun to perform operations on each cell
% The following command applies the function isempty to each cell
idx1 = ~cellfun(@isempty,A);
% indx1 has all zeroes indicating all cells are empty
% Add some random non-empty elements in the cell A
A{2,2} = [1,0;2,0;3,5];
A{2,3} = [4;5;6];
% Find all the non-empty cells
indx2 = ~cellfun(@isempty,A);
% indx2 gives the position of the non-empty cells
% Index into the non-empty cells
B = A(indx2);
% Find the last row element in each of the cells
% To return values in cell array, keep UniformOutput as false.
C = cellfun(@(x) x(end,:),B,'UniformOutput',false);
% The cell array C contains the last row in each of the non-empty cells
For more information, check out the cellfun documentation.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by