For loop with different length

18 次查看(过去 30 天)
Uerm
Uerm 2019-11-24
评论: Uerm 2019-11-25
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?

回答(1 个)

Roofus Milton
Roofus Milton 2019-11-25
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 个评论
Roofus Milton
Roofus Milton 2019-11-25
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 2019-11-25
Sorry, my bad. I have edited the original question. Thanks a lot, I will try the code to see if it works.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by