Extract arrays from cell with order in a for loop

23 views (last 30 days)
Hi,
I want to build a for loop which will extract cell datas into arrays (or matrices) . Let's say i got a cell A with the size of 1x12 and each cell in A has size of 25x1 array.
So is it possible to build a loop like this, (I'd like to name new array after its sequence in the for loop)
t = size(A,2);
for j=1:t
array_j = A{j};
end
or is there any other easy way to extract each cell into different arrays?
Thanks,
Görkem
  3 Comments
Stephen23
Stephen23 on 24 May 2021
"I'd like to name new array after its sequence in the for loop"
Naming arrays dynamically is one way that beginners force themselves into writing slow, inefficient, complex code:
Your code will be simpler and much more efficient if you use indexing, just like MATLAB was designed for.
"...is there any other easy way to extract each cell into different arrays"
The content of that cell array are already different arrays.
Görkem Bam
Görkem Bam on 25 May 2021
Thanks for advices.
I'd like to cut some elements from each array's first and last part and then reshape the remaining parts .For example I delete first 4 and last 3 elements in each array and then reshape to obtain 9x2 matrix from each one.
t = size(A,2);
for i=1:t
newArray(:,i) = A{i}; %Defined all cells into matrix
end
array_to_crop = newArray(:,1); %First array from matrix to crop
array_cropped = array_to_crop(5:22,1); %Cropping selected array
array_reshaped = reshape(array_cropped,9,[]) %Reshaping
This will give me the output but i need 12 of them. So i have to write this code for 12 times or higher for extended cases. I wanted to do this more efficient.
Thanks

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 25 May 2021
B = A;
for k = 1:numel(A)
array_to_crop = A{k};
array_cropped = array_to_crop(5:22,1); %Cropping selected array
B{k} = reshape(array_cropped,9,[]); %Reshaping
end
  2 Comments
the cyclist
the cyclist on 25 May 2021
Or never create the intermediate arrays, and work only with the original cell array:
B = A;
for k = 1:numel(A)
B{k} = reshape(A{k}(5:22,1),9,[]);
end
If you don't need original array, then you also don't need to create B and assign to it. You can just work on A directly.
for k = 1:numel(A)
A{k} = reshape(A{k}(5:22,1),9,[]);
end
You can also use cellfun rather than the loop:
A = cellfun(@(x)reshape(x(5:22,1),9,[]),A,'UniformOutput',false)
Which of this approaches is best for you may depend on the size of of A. Also, readability and whether "future you" understands what the code is doing is an important factor.

Sign in to comment.

More Answers (1)

David Hill
David Hill on 24 May 2021
t = size(A,2);
for j=1:t
newArray(j,:) = A{j}';%better to put into a matrix and just index into it than create a whole bunch of variable names
end

Products

Community Treasure Hunt

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

Start Hunting!