I need to calculate matrix b for each iteration from k value 0 to 1 with the step size of 0.01. How can I calculate the iteration using the for loop function and store all iteration outputs in matrix? Somebody please help me. Thank you.

1 view (last 30 days)
load acetylene
X= [x1,x2,x3];
k =1;
I=eye(size(X'*X));
b=((inv(X'*X+k*I))*X')*y;
for i=0:0.01:1
b(i)=((inv(X'*X+k(i)*I))*X')*y;
end
This is the code and I got the error message as below.
Attempted to access k(0); index must be a positive integer or logical.
Error in berlatih6 (line 14)
b(i)=((inv(X'*X+k(i)*I))*X')*y;

Accepted Answer

Walter Roberson
Walter Roberson on 7 Jun 2015
Edited: Walter Roberson on 7 Jun 2015
Generally speaking you should transform
for i = list of floating point values
calculation that produces one result for each i
end
to
ivals = list of floating point values
for J = 1 : length(ivals)
i = ivals(J);
outputvariable(J) = ....
end
except that you should avoid using a variable named "i" as "i" is the imaginary unit.
  3 Comments
Walter Roberson
Walter Roberson on 7 Jun 2015
outputvariable{J} = ....
If you want the results in an array then you will have to define which dimension the various values should be on. For example it is plausible that you want
outputvariable(:,:,J) = ....
but since we have no idea what the size() are of your variables or how you want the output arranged we can't say for sure.

Sign in to comment.

More Answers (1)

Roger Stafford
Roger Stafford on 7 Jun 2015
Edited: Roger Stafford on 7 Jun 2015
As you can determine by reading the Matlab documentation, you cannot have zero or fractional values for array indices as you have done in k(i) and b(i). You should do this instead:
k = 0:0.01:1;
b = zeros(length(k),1);
for ii = 1:length(k)
b(ii)=((inv(X'*X+k(ii)*I))*X')*y;
...
  1 Comment
Ahmad Zul Izzi Fauzi
Ahmad Zul Izzi Fauzi on 7 Jun 2015
Thank you for your answer. Now I got this error message.
In an assignment A(I) = B, the number of elements in B and I must be the same. What should I do then? Thanks.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!