For loop with different length

18 views (last 30 days)
Uerm
Uerm on 24 Nov 2019
Commented: Uerm on 25 Nov 2019
Hello,
I have a 1x10 cell (Var), where each cell is a 50*20000*A 3D array. I am trying to run the following code:
for k = 1:N
for j = 1:50
for i = 1:10
test{i} = mean(Var{i}(j,:,k));
test2{i} = std(Var{i}(j,:,k));
end
end
end
However, as apparent the number N will be different as A changes for each cell. How can I compute this with different N?

Answers (1)

Roofus Milton
Roofus Milton on 25 Nov 2019
See last section of code. I used a counter variable which is incremented.
rows = 50;
columns = 20000;
randRange = [10, 50];
% create the cell array
data = cell(1, 10);
% loop over cell array and create matricies with varying size of third
% dimension
for p = 1:length(data)
data{p} = rand(rows, columns, randi(randRange));
end
% get the size of each matrix
dimensions = cell2mat(cellfun(@size, data, 'UniformOutput', false)');
% calculate how many rows will be needed
totalRows = sum(dimensions(:, 1) .* dimensions(:, 3));
% preallocate the output matrix
output = zeros(totalRows, columns);
% initialize the counter variable
counter = 1;
% loop over cell
for i = 1:length(data)
% loop over rows
for j = 1:dimensions(i, 1)
% loop over third dimension
for k = 1:dimensions(i, 3)
% assign the data
output(counter, :) = data{i}(j, :, k);
% increment the counter
counter = counter + 1;
end
end
end
  3 Comments
Roofus Milton
Roofus Milton on 25 Nov 2019
This is really a different question. m, s, X, and Y are not defined in your code or mine. I believe the below accoplishes what you are getting at.
Replace the las two sections of code above with these snippets.
% preallocate the output matrix
outputData = zeros(totalRows, columns);
% create a cell array of functions you want to calculate
f = {@mean, @std};
% preallocate the stats matrix
outputStats = zeros(totalRows, length(f));
% initialize the counter variable
counter = 1;
% loop over cell
for i = 1:length(data)
% loop over rows
for j = 1:dimensions(i, 1)
% loop over third dimension
for k = 1:dimensions(i, 3)
% assign the data
outputData(counter, :) = data{i}(j, :, k);
% loop over the stats you want to calculate
for g = 1:length(f)
outputStats(counter, g) = f{g}(outputData(counter, :));
end
% increment the counter
counter = counter + 1;
end
end
end
output = {outputStats, outputData};
Uerm
Uerm on 25 Nov 2019
Sorry, my bad. I have edited the original question. Thanks a lot, I will try the code to see if it works.

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!