Replacing one value in a for loop
Show older comments
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.?
Answers (1)
Azzi Abdelmalek
on 6 Nov 2013
Edited: Azzi Abdelmalek
on 6 Nov 2013
Use circshift function
a=[1 0 0 0];
for k=1:3
b=circshift(a,[0 k])
%your code
end
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!