Reduce number of outputs in workspace

5 次查看(过去 30 天)
I am running some codes and getting too much outputs in the workspace, and that is confusing especially when you have a series of functions. So is there a way to reduce their number?
a=[2 3; 6 2; 4 1];
[m n] = size(a);
n = m;
Dist = zeros(m, n);
for i = 1 : m
for j = 1 : n
Dist(i, j) = sqrt((a(i, 1) - a(j, 1)) ^ 2 + ...
(a(i, 2) - a(j, 2)) ^ 2);
end
end
Dist
For example running this code, how can I get just 'a' and 'Dist' in workspace?

采纳的回答

Stephen23
Stephen23 2017-5-12
编辑:Stephen23 2017-5-12
Method One: write a function:
function D = myfun(a)
m = size(a,1);
D = zeros(m,m);
for i = 1:m
for j = 1:m
D(i,j) = sqrt((a(i,1) - a(j,1)) .^ 2 + ...
(a(i,2) - a(j,2)) .^ 2);
end
end
end
And then call it like this:
>> a = [2,3;6,2;4,1];
>> d = myfun(a)
d =
0.00000 4.12311 2.82843
4.12311 0.00000 2.23607
2.82843 2.23607 0.00000
Method Two: write simpler code: you do not need all of those variables:
>> d = sqrt(...
bsxfun(@minus,a(:,1),a(:,1).').^2 + ...
bsxfun(@minus,a(:,2),a(:,2).').^2)
d =
0.00000 4.12311 2.82843
4.12311 0.00000 2.23607
2.82843 2.23607 0.00000

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2017-5-12
编辑:Andrei Bobrov 2017-5-12
hypot(a(:,1) - a(:,1)',a(:,2) - a(:,2)')
or from Statistics and Machine Learning Toolbox
squareform(pdist(a))

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by