如何在Matlab中的for循环中计算值 [英] How to calculate the value within a for loop in matlab

查看:988
本文介绍了如何在Matlab中的for循环中计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个方程,但是我需要找到更广义的公式.我的程序如下:

I have already made one equation but I need to find more generalized formula. My program is below:

p2=[];
W=3;
i=6;

for a1=1:W
    for a2=a1:W
        for a3=a2:W
            for a4=a3:W
                for a5=i-a4-a3-a2-a1;
                    if(a4 <= a5 && a5<=W)
                        p2=[p2;a1,a2,a3,a4,a5];
                    end
                end
            end
        end
    end
end

在这里,如果a1=1然后a2=1,2,3,如果a1=2然后a2=2,3,如果a1=3然后a2=3. a3& a4. 现在我要使该程序仅依赖于Wi,并且我不想编写a1a2a3a4a5,而我只想声明然后a(1:5). 我已经尝试过,但无法取得丰硕的成果.

Here if a1=1 then a2=1,2,3, if a1=2 then a2=2,3 and if a1=3 then a2=3. The same condition is for a3 & a4. Now I want to make this program only depends on W and i and I don't want to write a1,a2,a3,a4,a5 rather I just want to declare then a(1:5). I have already tried but cannot get fruitful result.

Matlab专家,我真的需要您的帮助.

Matlab experts I really need your help.

先谢谢了.

推荐答案

我认为这可以满足您的要求:

I think this does what you want:

[a5 a4 a3 a2 a1]=ndgrid(1:W,1:W,1:W,1:W,1:W);
ind = find(a2>=a1&a3>=a2&a4>=a3&a5>=a4&a1+a2+a3+a4+a5==i)
p2 = [a1(ind) a2(ind) a3(ind) a4(ind) a5(ind)]

这篇关于如何在Matlab中的for循环中计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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