How can I store the outputs of my function into a matrix?

36 visualizaciones (últimos 30 días)
Hi,
I'm trying to preallocate my function so that it will return the outputs into a matrix, but it is currently only returning each output. This causes the output to be overwritten each time. I tried to set a matrix to zeroes with the desired size, but it does not fill the matrix.
For example, when inputting a simple matrix 'a',
9 1
10 3
2 6
10 10
7 10
I am getting back the following results:
d_array =
2.2361 1.0000 2.0000
d_array =
8.6023 1.0000 3.0000
d_array =
9.0554 1.0000 4.0000
d_array =
9.2195 1.0000 5.0000
d_array =
8.5440 2.0000 3.0000
d_array =
7 2 4
d_array =
7.6158 2.0000 5.0000
d_array =
8.9443 3.0000 4.0000
d_array =
6.4031 3.0000 5.0000
d_array =
3 4 5
d_array =
3 4 5
However, I want them to all appear in one matrix, stacked on top of each other in a 10 x 3. Also, I have no idea why the last value repeats itself.
Any ideas?
function d_array = d_calc(arr)
n = size(arr);
nrows = n(1,1);
ncol = n(1,2);
d_array = zeros(((nrows*(nrows-1))/2), ncol+1);
for i=1:(nrows)
for j=i+1:(nrows)
d = mydistance(arr(i,:), arr(j, :));
d_array = horzcat(d, i, j)
end
end
end
  1 comentario
Eric Martz
Eric Martz el 15 de Jul. de 2019
arr is any matrix. I am using 'a' currently:
a =
9 1
10 3
2 6
10 10
7 10

Iniciar sesión para comentar.

Respuesta aceptada

KALYAN ACHARJYA
KALYAN ACHARJYA el 15 de Jul. de 2019
Editada: KALYAN ACHARJYA el 15 de Jul. de 2019
#Edited:Initialize l=1 before for loop
d_array={};
m=1
for...
d_array{m}=horzcat(d, i, j);
m=m+1;
Save the all generated array in cell array.
  15 comentarios
Eric Martz
Eric Martz el 15 de Jul. de 2019
Woohoo! Thank you so much, Kalyan!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by