Extract arrays from cell with order in a for loop

5 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2021-5-24
"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 2021-5-25
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

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2021-5-25
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 个评论
the cyclist
the cyclist 2021-5-25
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.

请先登录,再进行评论。

更多回答(1 个)

David Hill
David Hill 2021-5-24
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by