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?
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