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
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.
采纳的回答
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
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
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!