How to loop the constant in a function?

I'm currently stuck on this most likely rather simple problem, but for some reason I can't get it to work. What I want to do is simply to solve the function f(x,k) for a grid of different k:s. As a very simple example, I'd want to solve
y=(x^2)+k for k=1:1:5
with some kind of for-loop, where the answer thus becomes a vector with 5 different answers. My main track has been to loop the command where I ask Matlab to solve the function, i.e. running a script like
for k=1:1:5
X = fminsearch(@ericr,-2,2)
end
where the function looks like
function [ y ] = ericr(x,k)
y=x^2 + k
end
MATLAB does not like this approach at all, and any help if therefore greatly appreciated!
Best regards,
Eric

 採用された回答

Eric
Eric 2013 年 10 月 10 日

0 投票

It turned out it was as easy as making sure "k" is a global variable (I forgot to write "global k" in both the script and the function file).

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2013 年 10 月 10 日

0 投票

What do you exactly mean by " solve the function "? Do you mean that you have a set of points (X,Y), and you want to fit the function
y = A*(X^2)+k
through it by looking for the value of A that minimises the distances between y and Y, given a specific value of k?

2 件のコメント

Eric
Eric 2013 年 10 月 10 日
Sorry; that was a bit of a sloppy notation on my part. What I meant by "solve" was to minimize y, i.e. for which x (given the k) do I find a local minimum?
Jos (10584)
Jos (10584) 2013 年 10 月 10 日
that would be at x = 0 for every k ... No need for matlab at all ;-)

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

Youssef  Khmou
Youssef Khmou 2013 年 10 月 10 日
編集済み: Youssef Khmou 2013 年 10 月 10 日

0 投票

Eric, use anonymous functions better,
Here is your example ( its obvious that k is the y solution):
N=10;
for k=1:N
f=@(x) (x.^2)+k;
[a,b]=fminsearch(f,rand);
X(k,1)=a;
X(k,2)=b;
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2013 年 10 月 10 日

コメント済み:

2013 年 10 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by