Vectorizing a multivariate function

Hello everyone
I have a problem to define a bivariate function using vectorization. I want to plot the function z = x1^2 + x2^2 which is a paraboloid.
I define x as:
x = [x1;x2];
z = x.' * x;
which means that z = x1^2 + x2^2 but it gives me the wrong answer. for example, for
x1 = linspace(-1,1,10);
x2 = linspace(-2,2,10);
when I define z = x.' * x the answer is wrong (however the size of z is correct and 10*10) but when I say
[X1,X2] = meshgrid(x1,x2)
z = X1.^2 + X2.^2
the answer is correct
I do not fully understand where I go wrong. I will appreciate your kindness in advance for helping me.

 採用された回答

Chunru
Chunru 2021 年 8 月 28 日

0 投票

Define ,
x = [x1;x2];
The x here is a matrix of 2 by n:
z = x.' * x;
Here z is matrix multiplication of (x.') and x.
The result z is an nxn matrix. But it does not mean that z = x1^2 + x2^2.
When you define x1 and x2 as follows:
[X1,X2] = meshgrid(x1,x2)
,
z = X1.^2 + X2.^2
Then X1.^2 is the element-by-element square, so that

3 件のコメント

Proman
Proman 2021 年 8 月 28 日
Thank you for your kind reply.
You are absolutely correct.
But I want to see if it is possible to define the function in matrix form (rather than the meshgrid form)?
Chunru
Chunru 2021 年 8 月 28 日
Yes. It's possible use automatic array expansion.
x = (1:5); % row vector
y = (0:10:60)'; % column vector
z = x.^2 + y.^2 % vectors expanded to compatible matrices
z = 7×5
1 4 9 16 25 101 104 109 116 125 401 404 409 416 425 901 904 909 916 925 1601 1604 1609 1616 1625 2501 2504 2509 2516 2525 3601 3604 3609 3616 3625
Proman
Proman 2021 年 8 月 28 日
Many thanks

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

リリース

R2019b

質問済み:

2021 年 8 月 27 日

コメント済み:

2021 年 8 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by