How can I define norm of a vector as a symbolic function?

2 次查看(过去 30 天)
I have defined the symbolic function as follows:
syms g(x,w)
g(x,w) = norm(w);
Then I have tested it using a symbolic variable:
v = sym('v', [1,2]);
g(x,v)
It only gives me the magnitude of of each entry of the vector, rather than the magnitude of the whole vector which is what I want:
ans =
[ (abs(v1)^2)^(1/2), (abs(v2)^2)^(1/2)]
How can I change it so it yields the norm of the whole vector? I would greatly appreciate your help!

采纳的回答

Stephan
Stephan 2019-3-1
编辑:Stephan 2019-3-1
Hi,
try:
syms g(x,v)
v = sym('v', [1,3]);
g(x,v) = norm(v)
g(x, v1, v2, v3) =
(abs(v1)^2 + abs(v2)^2 + abs(v3)^2)^(1/2)
>> pretty(g)
2 2 2
sqrt(|v1| + |v2| + |v3| )
Best regards
Stephan
  2 个评论
Jeff Lau
Jeff Lau 2019-3-1
Thanks for your comment. Also,I would like to be able to alter the size of the vector. (i.e v could be [1,4], [1,20] or even [1,100] etc.) Is there a way so that you don't need to specify the entries of v? (It would be quite time-consuming to type v1 up to v100 haha)
Stephan
Stephan 2019-3-1
编辑:Stephan 2019-3-1
You can:
v_elements = 10
syms g(x,v)
v = sym('v', [1,v_elements]);
g(x,v) = norm(v)
pretty(g)
with result:
2 2 2 2 2 2 2 2 2 2
sqrt(|v1| + |v2| + |v3| + |v4| + |v5| + |v6| + |v7| + |v8| + |v9| + |v10| )
If needed you could write a function with the length of v as input argument and as the result it gives the symbolic expression back:
result = give_symbolic_norm(6)
function result = give_symbolic_norm(num_v_elements)
syms g(x,v)
v = sym('v', [1,num_v_elements]);
g(x,v) = norm(v);
result = g;
end
With result:
result(x, v1, v2, v3, v4, v5, v6) =
(abs(v1)^2 + abs(v2)^2 + abs(v3)^2 + abs(v4)^2 + abs(v5)^2 + abs(v6)^2)^(1/2)
This has the advantage, that your base workspace keeps clean and only the resulting symbolic function is in it:
>> whos
Name Size Bytes Class Attributes
result 1x1 8 symfun

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by