Multiplying two vectors to form a matrix

Hello, I have two vectors x and y, both 601x1. I want to multiply them to form a matrix of 601x601, but the values inside the matrix have to be sqrt(x^2+y^2). How do I do this? Thanks.

 採用された回答

Jan
Jan 2022 年 2 月 25 日
編集済み: Jan 2022 年 2 月 25 日

0 投票

z = sqrt(x .^ 2 + y.' .^ 2)
But, of course, this does not match "multiply them". If you want a multiplication:
x .* y.'
[EDITED] For Matlab versions < R2016b:
z = sqrt(bsxfun(@plus, x.'.^2, y.^2))

2 件のコメント

Nikola Segedin
Nikola Segedin 2022 年 2 月 25 日
Multiplication is not the right word, I agree. I've tried this and all I got is "Error using plus, Matrix dimensions must agree.".
Jan
Jan 2022 年 2 月 25 日
See my comment under Walter's answer.

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

その他の回答 (2 件)

KSSV
KSSV 2022 年 2 月 25 日

1 投票

x = rand(601,1) ;
y = rand(601,1) ;
iwant = sqrt(x.^2+y'.^2) ;
size(iwant)
ans = 1×2
601 601
Walter Roberson
Walter Roberson 2022 年 2 月 25 日

1 投票

D = sqrt(x.'.^2 + y.^2)

4 件のコメント

Walter Roberson
Walter Roberson 2022 年 2 月 25 日
The difference between my answer and the nearly-simultaneous answers by @KSSV and @Jan is that I arranged for the x coordinates to run horizontally but they have the x coordinates run vertically.
Nikola Segedin
Nikola Segedin 2022 年 2 月 25 日
I've tried this and all I got is "Error using plus, Matrix dimensions must agree.".
Jan
Jan 2022 年 2 月 25 日
@Nikola Segedin: Which Matlab versionare you using? Since R2016b an "implicit expanding" is applied. For former versions:
D = sqrt(bsxfun(@plus, x.'.^2, y.^2))
Nikola Segedin
Nikola Segedin 2022 年 2 月 25 日
I'm using R2010b. Thank you, this works for me!

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

カテゴリ

製品

リリース

R2010b

タグ

質問済み:

2022 年 2 月 25 日

編集済み:

Jan
2022 年 2 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by