Perform action for Cell Array without using for loop

12 visualizaciones (últimos 30 días)
Joris
Joris el 29 de Jul. de 2021
Respondida: Salman Ahmed el 4 de Ag. de 2021
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

Respuesta aceptada

Salman Ahmed
Salman Ahmed el 4 de Ag. de 2021
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.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by