필터 지우기
필터 지우기

For loop with different length

조회 수: 27 (최근 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에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by