如何在 MATLAB 循环中创建/处理变量?
我需要计算多个变量的平均值、标准差和其他值,我想知道如何使用循环来发挥我的优势。我有 5 个电极的数据。因此,为了计算每个的平均值,我这样做:
mean_ch1 = mean(ch1);
mean_ch2 = mean(ch2);
mean_ch3 = mean(ch3);
mean_ch4 = mean(ch4);
mean_ch5 = mean(ch5);
我想要的是将代码压缩成一行左右。我尝试的代码不起作用:
for i = 1:5
mean_ch(i) = mean(ch(i));
end
我知道这段代码是错误的,但它传达了我想要完成的任务的想法。我希望最终得到 5 个单独的变量,这些变量由循环或元胞数组命名,其中包含所有 5 个变量,以便于调用。我知道必须有一种方法来编写这段代码,我只是不确定如何完成它。
I need to calculate the mean, standard deviation, and other values for a number of variables and I was wondering how to use a loop to my advantage. I have 5 electrodes of data. So to calculate the mean of each I do this:
mean_ch1 = mean(ch1);
mean_ch2 = mean(ch2);
mean_ch3 = mean(ch3);
mean_ch4 = mean(ch4);
mean_ch5 = mean(ch5);
What I want is to be able to condense that code into a line or so. The code I tried does not work:
for i = 1:5
mean_ch(i) = mean(ch(i));
end
I know this code is wrong but it conveys the idea of what I'm trying to accomplish. I want to end up with 5 separate variables that are named by the loop or a cell array with all 5 variables within it allowing for easy recall. I know there must be a way to write this code I'm just not sure how to accomplish it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您有几种选择来执行此操作:
您可以先将所有通道数据放入一个大矩阵中,然后使用函数 平均值。例如,如果每个 chX 变量都是 N×1 数组,您可以执行以下操作:
的每个单元格
即使每个
chX
数组的长度彼此不同,这也可以工作。您可以使用EVAL 生成单独的每个通道的变量平均值:
You have a few options for how you can do this:
You can put all your channel data into one large matrix first, then compute the mean of the rows or columns using the function MEAN. For example, if each
chX
variable is an N-by-1 array, you can do the following:You can put all your channel data into a cell array first, then compute the mean of each cell using the function CELLFUN:
This would work even if each
chX
array is a different length from one another.You can use EVAL to generate the separate variables for each channel mean:
如果它总是恰好 5 个通道,你可以做
一个更复杂的方法是
If it's always exactly 5 channels, you can do
A more complicated way would be
除了新手的回答。您可以使用结构和动态字段名称来完成您的任务。首先,我假设您的通道数据变量均采用 ch* 格式,并且是 MATLAB 工作区中唯一的变量。你可以做类似下面的事情
Apart from gnovice's answer. You could use structures and dynamic field names to accomplish your task. First I assume that your channel data variables are all in the format ch* and are the only variables in your MATLAB workspace. The you could do something like the following