如何使用for循环matlab调用顺序变量? [英] How to call sequential variables with for loop matlab?

查看:914
本文介绍了如何使用for循环matlab调用顺序变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆名为length_act_i的变量

i=1:6

我想在for循环中依次调用每个对象,但这是行不通的:

I'd like to call each one sequentially as part of a for loop, but this doesn't work:

for i=1:6
    I={['length_act_',num2str(i)]};
    subplot(3,2,i)
    [f x]=hist(I,1:2:5);
    bar(x,f./trapz(x,f),'barwidth',0.5,'r');
end

最有效的方法是什么?

此致

推荐答案

使用 eval 在循环中:

Use eval inside your loop:

eval(['I = length_act_', num2str(i)]);

专业提示:
eval命令通常很慢且效率低下,请改用数组.在您的情况下,似乎每个"length_act_i"变量本身都是向量,因此您应该使用单元格数组.例如,将其命名为length_act并进行如下设置:

Pro tip:
The eval command is usually slow and inefficient, use arrays instead. In your case, it seems that each of your "length_act_i" variables is a vector on its own, so you should be employing a cell array. For instance, call it length_act and set it like so:

length_act = {length_act_1, length_act_2, length_act_3, ...};

,然后使用以下命令访问数组中的每个单元格:

and then access each cell in the array using:

for i = 1:length(length_act)
    I = length_act{i};

    ...
end

此外,建议不要使用"i"和"j"作为变量的名称.

这篇关于如何使用for循环matlab调用顺序变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆