1
votes

I need help please, How do I return a matrix from a function in matlab? I have a matrix with zeros(size NxN). I send the matrix to some function to update her. How do I return the updated matrix?

in a code:

matrix = zeros(size); %put zeros
updateMatrix(radius,x0,y0,matrix);%call to function

function updateMatrix(radius,x0,y0,matrix)
    update the matrix
end

continue the prog with the updated matrix

I just need to return the updated matrix, and I don't change the other variables.

I tried to do this:

matrix = zeros(size); %put zeros
matrix=updateMatrix(radius,x0,y0,matrix);%call to function

function [matrix]=updateMatrix(radius,x0,y0,matrix)
    update the matrix
end

continue the prog with the updated matrix

But it doesn't work.

Thanks!

2

2 Answers

5
votes

Matlab doesn't support pointers, inputs cannot be altered unless specified. Try something like this.

matrix=updateMatrix(radius,x0,y0,matrix)    

function matrix=updateMatrix(radius,x0,y0,matrix)
    %update the matrix
end
2
votes

You can't pass a pointer or reference to a MATLAB function as you would in C or C++ (or any number of other languages) and have it operate on the data in-place. However, the MATLAB optimizer should be able to recognize cases where the intent is to mutate the data in-place within a function. This optimization was added several years ago.

Write your function as

function matrix = updateMatrix( radius, x0, y0, matrix )
  % do whatever to the matrix variable
end

Call it as

m = zeros( row, col );
m = updateMatrix( r, x0, y0, m );

The trick is to keep names of the input and output variables the same so that the optimizer realizes that you'd like to mutate the data in-place.