For loop with different length
18 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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
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};
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!