How can I perform Element wise Substitution using Subs without using 'for' loop?

2 ビュー (過去 30 日間)
Harshvardhan
Harshvardhan 2012 年 11 月 5 日
Hello Everyone
I would appreciate if anyone can help me understand how I can use 'subs' for simultaneous substitutions (row/column-wise) in a vector of functions. For example, if I enter
>> syms x y z a b
>> func =
[ x + y + 2*z;
x^2 + y^2 + 3;
3*y + z + 3];
>> subs(func, [x y; y z; z x]; [a b; b a; a a])
I expected to see
[a + b + 2*z;
x^2 + b^2 + 3;
3*y + a + 3]
(This because I want 'a' for 'x' and 'b' for 'y' only in the first function, 'b' for 'y' and 'a' for 'z' only in the second function and so on)
Instead, I see the following result
3*a + b
a^2 + b^2 + 3
a + 3*b + 3
I would like to have a simultaneous substitutions across functions to avoid writing a 'for' loop as I have to perform substitutions in a huge vector of functions and using a for loop is slowing down my program drastically.
Thanks

回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 11 月 5 日
When you subs() specifying a symbol, all occurrences of the symbol are replaced in the expression. When you subs() specifying an expression, only occurrences of the expression are substituted for, and all such occurrences are done -- but "hidden" occurrences of the expression are not touched. For example if you had 2*x + y and substituted on x + y then subs() would not know to break this down into x + x + y and do the substitution; it also might not find x + y in an expression x + z + y . You also cannot, in such a case, use a "pattern".
If you want to substitute into part of an expression, use indexing, or subsop(). See also the MuPAD match() routine.

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by