This MATLAB function returns a result vector.

If I have a function in MATLAB , and inside 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 to define a function to return these two variables, but with all the changes they carried in the loop, for example

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

Thus, instead, the function returns a single value. How to return a vector of results obtained from a loop?

+3
source share
2 answers

If I knew what you were trying to do at a higher level, I could give you better advice. When I read this question, I asked myself: "Why does he want to do this?" Most likely, there is a much better way to do what you are trying to do.

, , - .

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

, - , , , . , , , , - , /.

, , . , ? , ? ? , ?

, , :

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
+7
function [var1 var2] = my_func
    for n=1:5
        var1(n) = 2*n - 1;
        var2(:,:,n) = rand(3);  %create random 3x3 matrices 
    end

,

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


...
+2

Source: https://habr.com/ru/post/1791080/


All Articles