MATLAB Answers

0

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

Asked by Eric Martz on 15 Jul 2019
Latest activity Commented on by KALYAN ACHARJYA on 15 Jul 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 Comment

arr is any matrix. I am using 'a' currently:
a =
9 1
10 3
2 6
10 10
7 10

Sign in to comment.

1 Answer

Answer by KALYAN ACHARJYA on 15 Jul 2019
Edited by KALYAN ACHARJYA on 15 Jul 2019
 Accepted Answer

#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 Comments

Replace the file
function d_array = d_calc(arr)
n=size(arr);
nrows=n(1,1);
ncol=n(1,2);
d_array={};
m=1;
for i=1:nrows
for j=i+1:nrows
d=mydistance(arr(i,:), arr(j,:));
d_array{m}=horzcat(d,i,j);
m=m+1;
end
end
end
Result:
d_array =
1×10 cell array
Columns 1 through 7
[1×3 double] [1×3 double] [1×3 double] [1×3 double] [1×3 double] [1×3 double] [1×3 double]
Columns 8 through 10
[1×3 double] [1×3 double] [1×3 double]
Rest are same, please note multiple use of loops are no recomended, see vectorization.
Good Night!
Woohoo! Thank you so much, Kalyan!

Sign in to comment.