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

16 次查看(过去 30 天)
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

采纳的回答

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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by