This MATLAB function returns a vector of results

51.4k views Asked by At

If I have a function in MATLAB, and within it I have a loop, that calculates two variables, something like:

for index = 1:1000,
    var1 = 0.0;
    var2 = zeros(size(someMatrix));
    ...
    %some calculus...
    ...
end

How do I define the function to return those two variables, but with all changes they suffered while in the loop, like

var1 = [1, 3, 5, 7]
var2 = some matrix,

So instead the function returns a single value. How do I return a vector of results, gotten from the loop?

2

There are 2 answers

2
Miebster On BEST ANSWER

If I knew what you were trying to do at a higher level I might be able to give you better advice. When I read this question I ask myself "Why would he want to do that?". Chances are there is a much better way to do what you are trying to do.

That being said, I think you are attempting to do something like this.

function [x y] = foo
x = 0;
y = 0;
for i = 1:100
  if x(end)<i
      x(end+1)=i^2;
  end
  if y(end)^3<x(end)
      y(end+1)=sqrt(x(end));
  end
end

>> [x y] = foo
x =
     0     1     4    25   676
y =
     0     1     2     5    26

I'm not saying that this function is a good way of doing what you are trying to do, but I think it accomplishes the job. If it does, leave a comment, then maybe someone else can swing by and tell you how to do it more efficiently/safer.

The solution I provided is going to be prone to problems. If your variable changes twice in the same loop, do you want to see that or not? If you update one element of a matrix, do you want to see that or not? Can your variables change dimensions or types in the loop? If the variables don't change values in the loop, can you include those values anyways?

Perhaps this solution would work better for what you are trying to do:

function [xout yout] = foo
n=100;
x = 0;
y = 0;
xout = repmat(x,n,1);
yout = repmat(y,n,1);
for i = 1:n
  if x<i
      x=i^2;
      end
  if y^3<x
      y=sqrt(x);
  end
    xout(i)=x;
    yout(i)=y;
end
xout = unique(xout);
yout = unique(yout);

>> [x y] = foo

x =
     1
     4
    25
   676

y =
     1
     2
     5
    26
2
Lucas On
function [var1 var2] = my_func
    for n=1:5
        var1(n) = 2*n - 1;
        var2(:,:,n) = rand(3);  %create random 3x3 matrices 
    end

You can then call the function like this

>> [first second] = my_func

first =

     1     3     5     7     9


second(:,:,1) =

    0.3371    0.3112    0.6020
    0.1622    0.5285    0.2630
    0.7943    0.1656    0.6541


second(:,:,2) =

    0.6892    0.0838    0.1524
    0.7482    0.2290    0.8258
    0.4505    0.9133    0.5383


...