Perform action for Cell Array without using for loop
조회 수: 12 (최근 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
댓글 수: 0
채택된 답변
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
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!