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 :(

조회 수: 12 (최근 30일)
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
Nikolas Katsantonis
Nikolas Katsantonis 2022년 6월 17일
Bsicly the matrix is created however the older values are saved as 0s and only the last value of the loop is saved
Geoff Hayes
Geoff Hayes 2022년 6월 17일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Geoff Hayes
Geoff Hayes 2022년 6월 17일
@Nikolas Katsantonis - you are using a as an integer and as a result from test
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).
  댓글 수: 4
Geoff Hayes
Geoff Hayes 2022년 6월 17일
You could try changing this code to
function [A, B]= test(n,Coordinates)
A = Coordinates*3;
B = A*Coordinates*6;
end
though the n can be removed since it is no longer relevant. It isn't clear to me why b isn't being set...it does for me when I try it.
A couple more things from
function [myData1,aValue,bValue,n] = Untitleddd(Coordinates)
a=5;
myData1 = zeros(a,1);% Added
for n=1:a
Coordinates=3+n;
[aValue, bValue] = test(n,Coordinates);
myData1(n)= aValue(n);%Added
end
end
Coordinates is passed in as an input parameter but is reset with 3+n. Is this intentional? Also, since test doesn't return arrays, then just do
myData1(n)= aValue;

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Complex Numbers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by