how do I put arrays into a for loop

1 次查看(过去 30 天)
I have a .mat file. There are 24 array in this file. I want to calculate the mean of the first N elements of an array.
But what I want is for the 24 directories in the .mat file to automatically enter this into a for loop. I am waiting for your help in this matter.
  2 个评论
Stephen23
Stephen23 2021-4-15
编辑:Stephen23 2021-4-15
"There are 24 array in this file. Array names like y1, y2 ... "
The most important thing is to load into an output variable:
S = load(...);
then you can trivially access the fieldnames of the structure S:
Loop over the fieldnames, allocate the data to an array, perform your calculation on the array. Done.
Rik
Rik 2021-4-23
Backup of this question:
how do I put arrays into a for loop
I have a .mat file. There are 24 array in this file. I want to calculate the mean of the first N elements of an array.
But what I want is for the 24 directories in the .mat file to automatically enter this into a for loop. I am waiting for your help in this matter.

请先登录,再进行评论。

采纳的回答

SungJun Cho
SungJun Cho 2021-4-15
编辑:SungJun Cho 2021-4-15
To calculate the mean of the first N elements of an array, you can use
mean_y1 = mean(y1(1:N));
However, you may import a .mat file which I suppose will give you a matrix in which each row or column is one array. In that case, just perform
mean_mat = mean(Y(:,1:N),2); % if each row is an array
mean_mat = mean(Y(1:N,:),1); % if each column is an array
and you will get a matrix containing the mean of first N elements of each array.
This should be a more efficient way to compute the mean than to use a for loop, but if using a for-loop is necessary, feel free to let me know.
  9 个评论
SungJun Cho
SungJun Cho 2021-4-15
No problem!
I imported your data as a structure type, then converted it into a cell type using "struct2cell". Once the data was converted, I noticed that the arrays named "y" (e.g., y1, y10, etc.) were located from 30th to 53rd rows of the data, so I extracted only those arrays so that the variable "Y" contains only the y arrays.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by