Extracting from cell arrays using a nested loop
Show older comments
I have a 1x250 cell array. Each cell contains an 87001x16 matrix. I want to extract all of the first column from cell 1, column 1 from cell 2, column 1 from cell 3, ... column 1 from cell 250, to create a 87001x250 matrix. And I want to do this with all 16 columns, creating a separate 1x16 cell array, with each cell containing an 87001x250 matrix.
When I run the following code, I get a 1x16 cell array, with each cell being the first 16 columns of the 250th cell:
for k = 1:250
Data{k} = Matrix(zapTime(k)-12000:zapTime(k)+75000, 2:end); % Yields 1x250 cell array, with 87001x16 matrices.
for c = 1:16
subData{c} = Data{k}(:,c); % Creates 1x16 cell array, with first 16 columns from Data cell #250.
end
end
When I run this code, I get a 1x16 cell array, with each cell being the matrices from the first 16 cells.
for k = 1:250
Data{k} = Matrix(zapTime(k)-12000:zapTime(k)+75000, 2:end); % Yields 1x250 cell array, with 87001x16 matrices.
for c = 1:16
subData{c} = Data(:,c); % Creates 1x16 cell array, with first 16 matrices from Data cell array.
end
end
I'm able to code things separately just fine when I use the following code:
subData{k} = Data{k}(:,1);
subData{k} = Data{k}(:,2);
subData{k} = Data{k}(:,3);
...
subData{k} = Data{k}(:,16);
But certainly a nested loop would be more efficiant. When I try this...:
for c = 1:16
subData{k} = Data{k}(:,c);
end
...I get 250 cells of the data from columns 16.
Please help! Thank you!
Accepted Answer
More Answers (1)
Do not use a nested loop:
clear Data
for k=250:-1:1
Data(:,k,:) = Matrix(zapTime(k)-12000:zapTime(k)+75000, 2:end) );
end
subData=reshape( num2cell(Data,[1,2]) ,1,[]) ;
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!