I need an answer ASAP please!

# I want to use a for loop inside a function, where the for loop contains a subfuction. Each loop must store the variable value and make a matrix of all values, but I get 0s :(

2 views (last 30 days)

Show older comments

Nikolas Katsantonis
on 17 Jun 2022

Commented: Nikolas Katsantonis
on 18 Jun 2022

function [a] = Main(Coordinates)

a=5;

for n=1:a

Coordinates=3+n;

a= test(n,Coordinates)

end

end

function [A, B]= test(n,Coordinates)

A(n)= Coordinates*3;

B(n)= A(n)*Coordinates*6;

end

##### 3 Comments

Geoff Hayes
on 17 Jun 2022

That makes sense, right? Look at this code

function [A, B]= test(n,Coordinates)

A(n)= Coordinates*3;

B(n)= A(n)*Coordinates*6;

end

You are creating a new A and B whenever the test function is called. These new variables/arrays won't have the history from previous calls to this function. So you are always returning arrays of zeros except for the nth value which is set in this function call.

### Accepted Answer

Geoff Hayes
on 17 Jun 2022

a=5;

for n=1:a %<--- a as integer

Coordinates=3+n;

a= test(n,Coordinates) %<--- a as result

end

test should be returning two values and not arrays (you will need to correct this code), and so you would do something like

a=5;

for n=1:a

Coordinates=3+n;

[aValue, bValue] = test(n,Coordinates);

end

then store aValue into an array so that you don't overwrite it on each iteration of the loop

a=5;

myData = zeros(a,1);

for n=1:a

Coordinates=3+n;

[aValue, bValue] = test(n,Coordinates);

myData(n) = aValue;

end

then return myData in the signature of your function (not a).

### More Answers (0)

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!