MATLAB: Reduce number of outputs in workspace

workspace

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?

Best Answer

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