I am trying to calculate the partial derivatives of a user inputted function. For this, I ask for the function, and then the starting point.
From the starting point, I assume that each variable is presented, such that I can use
numberofvar = length(x);
h=0.0000000000000000000001;
grad= zeros (length(x),1);
This will give me my value of say [0 0 0 0] for instance.
I have
for i=1:length(x);
ei=zeros(length(x),1);
e(i) = 1;
gradient(i) = (feval(f,x+h*ei)-feval(f,x))/h;
end
I find the derivative in respect to each by calculating the lim of the function as it approaches h.
For each value, I want to, for instance multiply [1 0 0 0] by the function with four variables to find the derivative in respect to the first variable, then [0 1 0 0] to find the derivative in respect to the 2nd variable, and etc.
How can I make my for loop change the ei value to each scalar with [1 0 0 0] for iteration 1, [0 1 0 0] for iteration 2, [0 0 1 0] for iteration 3, and etc.?

回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 6 日
編集済み: Azzi Abdelmalek 2013 年 11 月 6 日

0 投票

Use circshift function
a=[1 0 0 0];
for k=1:3
b=circshift(a,[0 k])
%your code
end

カテゴリ

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

質問済み:

2013 年 11 月 6 日

編集済み:

2013 年 11 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by