Problem with indexing within a vector

3 ビュー (過去 30 日間)
K E
K E 2013 年 3 月 13 日
I have two vectors, x and y. I would like to make third vector, z, which has the combined magnitude of x and y, i.e. sqrt(x.^2 + y.^2) but has the sign of whichever of x and y has the bigger individual magnitude. If the example below, z should be [-10.20 5.39 10.77 -10.44]. However I am incorrectly indexing the matrix bothVectorsTogether, so that it returns a 4x4 matrix instead of a 4x1 vector. What is the right way to index it? The "real" x and y have 950000 elements so I want to avoid looping through each row to identify the sign.
% Initialize example vectors
x = [-10 5 4 -10]';
y = [2 -2 10 -3]';
zMagnitude = sqrt(x.^2 + y.^2); % Size 4x1
% Find which has a bigger individual magnitude, x or y
[~, whichIsBigger] = max(abs([x y])'); % 1 if x is bigger, 2 if y is bigger
bothVectorsTogether = [x y];
zSign = sign(bothVectorsTogether(:, whichIsBigger)); % Size 4x4 not 4x1
z = zMagnitude.*zSign;

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 13 日
編集済み: Azzi Abdelmalek 2013 年 3 月 13 日
x = [-10 5 4 -10]';
y = [2 -2 10 -3]';
idx=abs(x)>abs(y);
s=y;
s(idx)=x(idx);
z=sqrt(x.^2 + y.^2).*sign(s)
  1 件のコメント
K E
K E 2013 年 3 月 13 日
Works perfectly, thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by