Store equal size matrices in an array of unknown size

Im trying to create a program for gradient descent optimization of n variables and I've come across an issue of wanting to store {x1, x2, x3...xn} values at point i on each iteration of my while loop. This way I can call back to the array for each iteration to find xi+1. How do I store the x value matrices in an array of size n where we do not know how many n values there will be until we've reached out exiting criteria. Any help would be great.
function [xf, yf] = gradientOp(f, x0, n, tol)
% f is the function
% x0 is the initial value
% n is the learning rate
% tol is the change from xi+1 - xi
vars = symvar(f);
g = gradient(f);
cond = 1;
i = 1;
x = [];
x(1) = x0;
maxi = 10;
while ((cond > eps && h < tol) || i > maxi)
s = double(subs(g, vars, x(i))); % Computer gradient and x
if s == 0
break;
end
x(i+1) = x(i) - n*s;
h = x(i+1) - x(i);
if h < tol
xf = x(i);
yf = double(subs(f, vars, xf));
cond = 1;
end
i = i + 1;
end
end

9 Commenti

It appear that you know the maximum number of iterations maxi (note that the correct condition is i < maxi). Can't you just initialize it with zeros
z = zeros(1, maxi)
maxi is merely a fail-safe incase we dont reach the other criteria of our while loop.
I could use as part of the cell dimensions, but would that not leave a bunch of empty zero cells if we dont reach imax?
Then after the end of while loop add the line
x(i:end) = [];
It will remove all the extra zeros. Although you may think it is wastage of memory, I am sure that for large enough iterations, it will much faster than the dynamic allocation.
with
x = zeros(1, maxi);
x(i:end) = [];
x(1, 1) = x0;
I get the error
>> gradientOp(f, x, 0.5, 0.01)
Unable to perform assignment because the size of the left
side is 1-by-1 and the size of the right side is 1-by-2.
Error in gradientOp (line 13)
x(1, 2) = x0;
I suggested to add this line after the end of while loop, like this
x = zeros(1, maxi);
x(1) = x0;
maxi = 10;
while ((cond > eps && h < tol) || i > maxi)
% your code
end
x(i:end) = [];
Even with this change, I recieve the error
Unable to perform assignment because the size of the left
side is 1-by-1 and the size of the right side is 1-by-2.
which line gives this error?
@Isaac Hargrave Can you provide details on what input arguments you are passing to the function gradientOp and paste the exact error present in the command window including the line where you are getting the error.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Prodotti

Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by