# Save the values of a function in a for loop

조회 수: 31(최근 30일)
Austin Hernandez 2020년 4월 27일
댓글: Mrutyunjaya Hiremath 2020년 4월 27일
I need to record the y-values of a line from x=a to x=b.
Each loop, the slope of the line will change so there will be a different set of x and y's for each loop
How can I record the y-values from the function for each loop? The above fix doesn't work if a function is inside of it. This is my code and gives me an error once it trys to record y(i):
function for_test
x = 0:1:10;
y = ones(size(x)) ;
for i=1:10
y(i) = x+rand;
y % use y(i) so that it is written as a vector
end
end
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Austin Hernandez 2020년 4월 27일
That is the exact error message I am getting but my question was how do I store each y values for each through each loop? I think I found a workaround, and that is to put the data into a cell array with {i}. Is that the proper fix or is there another way?

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

### 채택된 답변

Mrutyunjaya Hiremath 2020년 4월 27일
Hell Austin Hernandez,
you are correct. but Option01 is good.
Option 01:
function for_test
x = 0:1:10;
y = zeros(size(x)) ;
for i=1:10
y(i,:) = x+rand;
y % use y(i) so that it is written as a vector
end
end
Option 02:
function for_test
x = 0:1:10;
y = {}; %ones(size(x)) ;
for i=1:10
y{i} = x+rand;
y % use y(i) so that it is written as a vector
end
end
##### 댓글 수: 5표시숨기기 이전 댓글 수: 4
Mrutyunjaya Hiremath 2020년 4월 27일
@ Austin,
Thank you
And, Initialize the values with One NOT Zero ...
c = 1;
m = 1;
u = 1;

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

R2020a

### Community Treasure Hunt

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

Start Hunting!