Borrar filtros
Borrar filtros

Reduce number of outputs in workspace

5 visualizaciones (últimos 30 días)
Asim Ismail
Asim Ismail el 12 de Mayo de 2017
Comentada: Asim Ismail el 12 de Mayo de 2017
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?

Respuesta aceptada

Stephen23
Stephen23 el 12 de Mayo de 2017
Editada: Stephen23 el 12 de Mayo de 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
  1 comentario
Asim Ismail
Asim Ismail el 12 de Mayo de 2017
Editada: Asim Ismail el 12 de Mayo de 2017
Thank you very much @Stephen

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 12 de Mayo de 2017
Editada: Andrei Bobrov el 12 de Mayo de 2017
hypot(a(:,1) - a(:,1)',a(:,2) - a(:,2)')
or from Statistics and Machine Learning Toolbox
squareform(pdist(a))

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by