Reduce number of outputs in workspace
9 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Stephen23
on 12 May 2017
Edited: Stephen23
on 12 May 2017
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
More Answers (1)
Andrei Bobrov
on 12 May 2017
Edited: Andrei Bobrov
on 12 May 2017
hypot(a(:,1) - a(:,1)',a(:,2) - a(:,2)')
or from Statistics and Machine Learning Toolbox
squareform(pdist(a))
See Also
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!