Storing function and variable values as the function runs

7 ビュー (過去 30 日間)
Kim
Kim 2014 年 11 月 18 日
コメント済み: Adam 2014 年 11 月 18 日
I know this must be very simple but please help if you can! I have the following code. I am trying to find out values of p for every possible value of r and c. I would also like to store the function value along with the variable values in a matrix. I can't seem to do any of it and I'm fairly sure what I am generating isn't right. Please help!
function p= penalty(r,c) %r =current point value %c= current penalty
p= ((r/150).^-2)*c; end
%find values of p for varying values of r and c clear f; for k=1 for i=1 while k<200 while i<200
f(k, i)=penalty(k,i);
k=k+1
i=i+1
end
end
end
end

採用された回答

Adam
Adam 2014 年 11 月 18 日
編集済み: Adam 2014 年 11 月 18 日
for k=1:200
for i=1:200
f(k, i)=penalty(k,i);
end
end
is the simplest change to your code to work using loops.
Don't mix for and while together. For is a loop, you don't want while in there as well as for.
If you want a vectorised version, change your function to:
function p= penalty(r,c) %r =current point value %c= current penalty
p = ((r'/150).^-2) * c;
end
and the call to simply:
k = 1:200;
i = 1:200;
f = penalty(k,i);
  2 件のコメント
Kim
Kim 2014 年 11 月 18 日
Thank you so much. I am so new to code writing and finding it hard to implement even simple mathematics!
Adam
Adam 2014 年 11 月 18 日
Note I just edited that answer to include the vectorised version.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by