Store equal size matrices in an array of unknown size
Mostra commenti meno recenti
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
Ameer Hamza
il 27 Mar 2020
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)
Isaac Hargrave
il 27 Mar 2020
Isaac Hargrave
il 27 Mar 2020
Ameer Hamza
il 27 Mar 2020
Modificato: Ameer Hamza
il 27 Mar 2020
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.
Isaac Hargrave
il 27 Mar 2020
Ameer Hamza
il 27 Mar 2020
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) = [];
Isaac Hargrave
il 27 Mar 2020
Ameer Hamza
il 27 Mar 2020
which line gives this error?
Srivardhan Gadila
il 2 Apr 2020
@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.
Risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!