フィルターのクリア

how to simplify a series of command

1 回表示 (過去 30 日間)
ZENONG
ZENONG 2023 年 6 月 15 日
編集済み: Dyuman Joshi 2023 年 6 月 15 日
hi, I did not study MATLAB systematically so this might be a basic question. is there a common method to simplifying series of commands like the first 34 lines of this file? Thank you.

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 6 月 15 日
編集済み: Dyuman Joshi 2023 年 6 月 15 日
This is the downside of dynamically naming variables.
Define an array instead of defining variables individually and use a loop -
%Defining an array where one can easily access values via simple indexing
p=[0,0,2; 2,0,2; 2,0,-1; -2,0,-1; -2,0,0; -1,0,1];
Q=[-1,0,0; 0,0,1; 2,0,0];
s1 = size(Q,1);
s2 = size(p,1);
%pre-allocation
out = zeros(s2,s1);
for m=1:s1
out(:,m)=1./vecnorm(Q(m,:)-p,2,2);
end
%Here (i,j) element of out corresponds to the value PQipj
out
out = 6×3
0.4472 1.0000 0.3536 0.2774 0.4472 0.5000 0.3162 0.3536 1.0000 0.7071 0.3536 0.2425 1.0000 0.4472 0.2500 1.0000 1.0000 0.3162
Edit - If you have the Stats and ML Toolbox, you can achieve the result in one line of code -
OUT = 1./pdist2(p,Q)
OUT = 6×3
0.4472 1.0000 0.3536 0.2774 0.4472 0.5000 0.3162 0.3536 1.0000 0.7071 0.3536 0.2425 1.0000 0.4472 0.2500 1.0000 1.0000 0.3162

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by