How do I vectorize the following code?

Hi,
I'm having trouble vectorizing the following code. The result should be a matrix with an upper triangle.
data = 1:1:10;
nn = length(data);
for x = 1:nn
for y = x:nn
X(x,y) = (data(y) - data(x)) / data(x);
end
end
All help gratefully received!

 採用された回答

Matt J
Matt J 2018 年 1 月 18 日

0 投票

X = triu(data(:)./data(:).' - 1)

4 件のコメント

David
David 2018 年 1 月 18 日
Hi, Thanks for this. This doesn't replicate the loop answers. Note y = x:nn.
Matt J
Matt J 2018 年 1 月 18 日
Just reverse the slash,
X = triu(data(:).\data(:).' - 1)
David
David 2018 年 1 月 18 日
That does it! Many thanks.
Matt J
Matt J 2018 年 1 月 18 日
You're welcome, but please Accept-click the answer to signify that it solved your problem.

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

その他の回答 (0 件)

カテゴリ

タグ

質問済み:

2018 年 1 月 18 日

コメント済み:

2018 年 1 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by