how to simplify a series of command
5 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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
Edit - If you have the Stats and ML Toolbox, you can achieve the result in one line of code -
OUT = 1./pdist2(p,Q)
1 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!