10 views (last 30 days)

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

Mrutyunjaya Hiremath
on 27 Apr 2020

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

Mrutyunjaya Hiremath
on 27 Apr 2020

Hello Austin,

Answer is in your problem only....

h = 0:1:10

y = zeros(size(h));

v = zeros(size(h));

o = zeros(size(h));

prompts = {'enter 1'};

dlg = 'title';

c = 0;

m = 0;

u = 0;

hold on

for i=1:5

A = inputdlg(prompts, dlg);

Aa = str2double(A);

x = Aa(1);

if x == 1

y(m,:) = 1000*h;

m = m + 1;

plot(h,y(m,:));

elseif x == 0

v(u,:) = h+1;

u = u + 1;

plot(h,v(u,:));

else

o(c,:) = -h*5;

c = c + 1;

plot(h,o(c,:));

end

end

end

Mrutyunjaya Hiremath
on 27 Apr 2020

@ Austin,

Thank you

And, Initialize the values with One NOT Zero ...

c = 1;

m = 1;

u = 1;

Opportunities for recent engineering grads.

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

Start Hunting!
## 2 Comments

## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/520954-save-the-values-of-a-function-in-a-for-loop#comment_835992

⋮## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/520954-save-the-values-of-a-function-in-a-for-loop#comment_835992

## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/520954-save-the-values-of-a-function-in-a-for-loop#comment_835996

⋮## Direct link to this comment

https://nl.mathworks.com/matlabcentral/answers/520954-save-the-values-of-a-function-in-a-for-loop#comment_835996

Sign in to comment.