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

조회 수: 35 (최근 30일)
Eric Martz
Eric Martz 2019년 7월 15일
댓글: KALYAN ACHARJYA 2019년 7월 15일
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
Eric Martz
Eric Martz 2019년 7월 15일
arr is any matrix. I am using 'a' currently:
a =
9 1
10 3
2 6
10 10
7 10

댓글을 달려면 로그인하십시오.

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 7월 15일
편집: KALYAN ACHARJYA 2019년 7월 15일
#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
Eric Martz
Eric Martz 2019년 7월 15일
Woohoo! Thank you so much, Kalyan!
KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 7월 15일
Welcome @Eric

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by