For loop with different length
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Roofus Milton
am 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 Kommentare
Roofus Milton
am 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};
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!