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 Ansicht (letzte 30 Tage)
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;

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 7 Jun. 2015
Bearbeitet: Walter Roberson am 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 Kommentare
Walter Roberson
Walter Roberson am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 7 Jun. 2015
Bearbeitet: Roger Stafford am 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 Kommentar
Ahmad Zul Izzi Fauzi
Ahmad Zul Izzi Fauzi am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by