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

35 vues (au cours des 30 derniers jours)
Eric Martz
Eric Martz le 15 Juil 2019
Commenté : KALYAN ACHARJYA le 15 Juil 2019
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 commentaire
Eric Martz
Eric Martz le 15 Juil 2019
arr is any matrix. I am using 'a' currently:
a =
9 1
10 3
2 6
10 10
7 10

Connectez-vous pour commenter.

Réponse acceptée

KALYAN ACHARJYA
KALYAN ACHARJYA le 15 Juil 2019
Modifié(e) : KALYAN ACHARJYA le 15 Juil 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 commentaires
Eric Martz
Eric Martz le 15 Juil 2019
Woohoo! Thank you so much, Kalyan!
KALYAN ACHARJYA
KALYAN ACHARJYA le 15 Juil 2019
Welcome @Eric

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by