# Extract arrays from cell with order in a for loop

25 visualizaciones (últimos 30 días)
Görkem Bam el 24 de Mayo de 2021
Comentada: the cyclist el 25 de Mayo de 2021
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 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Görkem Bam el 25 de Mayo de 2021
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

Iniciar sesión para comentar.

Stephen23 el 25 de Mayo de 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 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
the cyclist el 25 de Mayo de 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.

Iniciar sesión para comentar.

### Más respuestas (1)

David Hill el 24 de Mayo de 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
##### 1 comentarioMostrar NingunoOcultar Ninguno
Görkem Bam el 25 de Mayo de 2021
Thanks

Iniciar sesión para comentar.

### Categorías

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

### Community Treasure Hunt

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

Start Hunting!