Are symbolic indexing possible in matlab?

馋奶兔 提交于 2019-12-29 09:20:10

问题


I have such a function lnn1c(ii, j, n, n1) which takes indexes ii and jj as arguments where Kdk1 and Wdg are some arrays, wg(n) is another function kinda alpha*(n-3) and Gdg is a symbolic variable.

function lnn1c=lnn1c(ii, j, n, n1)
    syms k1Vzdg
    global Gdg Wdg Kdk1
    lnn1c=Gdg-i*(-(Wdg(ii)-Wdg(j))+(wg(n)-wg(n1))+...
        (Kdk1(ii)-Kdk1(j))*k1Vzdg);
end

I wanna perform in my script summation of expression lnn1c(ii, j, n, n1) over indexes ii and j from 1 up to 4. I tried such code

syms ii jj n n1
sum(subs(sum(subs(lnn1c(ii, jj, n, n1), ii, 1:4)),jj, 1:4))

but I keep getting such error

Indexing input must be numeric, logical or ':'.

Any help would be really valuable for me.


回答1:


No, symbolic indexing makes no sense.

However, you may be mixing ideas. You are effectively doing subs(f(ii, jj, n, n1), ii, 1:4). You put ii and then substitute it by 1:4. Why not put 1:4 as input?

Just do:

for jj=1:4
    s=s+sum(lnn1c(1:4, jj, n, n1));
end

Surely you will need numeric values for n and n1.... As you haven't shown the whole code, its hard to know what you are doing, but there are hints to say that you do not need symbolic maths at all and you are just mixing programming concepts.




回答2:


As Ander points out, you can do it in two for loops and you'll have no problem:

s=0;
for jj=1:4
    for ii=1:4
    s=s+sum(lnn1c(ii, jj, n, n1));
    end
end

However, if your intention is to do it in 1 line, why don't you try arrayfun?

s=sum(arrayfun(@(ii) sum(arrayfun(@(jj) lnn1c(ii, jj, n, n1),1:4),1:4));

And no need for syms ;)



来源:https://stackoverflow.com/questions/42295215/are-symbolic-indexing-possible-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!