Output of loop is 2x1 vector

3 ビュー (過去 30 日間)
mgc872
mgc872 2021 年 11 月 5 日
コメント済み: Walter Roberson 2024 年 10 月 28 日
I am trying to perform a manual computation of gradient descent, but having trouble with the for loop in storing the output as a vector (2x1 in this case).
With my inputs:
m=20x2 vector
f=20x1 vector
I have set up this for loop:
length= 10000; %k steps
c = 0.000001; %constant
a0 = [1;1] %first guess
a(1) = a0 -c * M' * (M* a0 -f) %first computation
for k=2:length
a(k) = a(k-1) - c * M' * (M * a(k-1) - f);
end
Unfortunately, I'm seeing `Unable to perform assignment because the left and right sides have a different number
of elements.`
I've verified that the output of the single-case computation a = a0 - c * M' * (M* a0 -f) is [a1;a2]. This is correct.
My question is how one stores an 'a1, a2' vector as the loop continuously iterates and updates the 'a1, a2' ?

採用された回答

Jon
Jon 2021 年 11 月 5 日
編集済み: Jon 2021 年 11 月 5 日
If you want to store the results of each loop in a 2 by numSteps matrix you can do this
numSteps= 10000; %k steps
c = 0.000001; %constant
a0 = [1;1] %first guess
% preallocate array to hold results
a = zeros(2,numSteps)
a(:,1) = a0 -c * M' * (M* a0 -f) %first computation
for k=2:length
a(:,k) = a(k-1) - c * M' * (M * a(k-1) - f);
end
Note, I changed your variable name from length to numSteps, length is a Matlab command that gives the maximum dimension of a matrix. Using it as a variable name will work, the variable assignment supersedes the MATLAB function, but is confusing if you think length is a function
  3 件のコメント
Jon
Jon 2021 年 11 月 5 日
oops, need to pull vectors out of a matrix on right hand side too does this help?
a(:,k) = a(:,k-1) - c * M' * (M * a(:,k-1) - f);
Jon
Jon 2021 年 11 月 5 日
If this doesn't work, could you please provide a little more of your example so that I can actually run it (I think I need something that defines M and -f to run it)

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

その他の回答 (1 件)

Solomon
Solomon 2024 年 10 月 28 日
no
  1 件のコメント
Walter Roberson
Walter Roberson 2024 年 10 月 28 日
I am having trouble figuring out how "no" is an Answer to the problem the user posed? It certainly is possible to store output vectors, so I am having trouble figuring out what the "no" is in response to?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by