How do I put arrays into a for loop

조회 수: 1 (최근 30일)
studentmatlaber
studentmatlaber 2021년 3월 31일
댓글: Image Analyst 2021년 3월 31일
I have 24 arrays (such as y1, y2, y3 ...). I want to calculate the average of each of the N elements of these arrays. For example, first the average of the first N elements of the y1 array will be calculated. After calculating the average of the first N elements of 24 arrays, I want it to be saved in an array.
I wrote the following code for this, but I can only calculate for a array.
N = 5;
sub = 0;
for i = 1: 1: N
sub = sub + y1 (i);
end
mean = sub / N;
  댓글 수: 1
Stephen23
Stephen23 2021년 3월 31일
"I have 24 arrays (such as y1, y2, y3 ...)."
How did you get all of those arrays into the workspace? Did you write them all out by hand?
"I want to calculate the average of each of the N elements of these arrays."
That would be a trivially easy task if you designed your data better (i.e. used one array and indexing).

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2021년 3월 31일
편집: Jan 2021년 3월 31일
Hiding an index in the name of a set of variables is the main problem here. This makes it hard to access the variables. Use an index instead:
Data = {y1, y2, y3, y4}; % et.c...
% Much better: Do not create y1, y2, ... at all, but the array directly
MeanData = zeros(1, numel(Data));
for k = 1:numel(Data)
MeanData{k} = mean(Data{k});
end
If there is any reason not to use the mean() function:
MeanData = zeros(1, numel(Data));
for k = 1:numel(Data)
MeanData{k} = sum(Data{k}) / numel(Data{k});
end
  댓글 수: 1
Image Analyst
Image Analyst 2021년 3월 31일
To get the mean of only the first N elements
for k = 1:numel(Data)
thisArray = Data{k};
MeanData(k) = mean(thisArray(1 : N));
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by