Save For loop results to vector/matrix
Mostra commenti meno recenti
I have a for loop that calculates the u-values of a function with a two step taylor series, but every iteration overwrites the variable. If I have a step size dx=[1 .5 .1] I want u to be displayed with the values of each iteration of u for each step size. Right now the result will display as u= [335 358.75 378.35] with u=335 for dx=1
%initailze the derivative of u, u_prime, and the step size, dx
u_prime=@(x)(x^2+4);
dx = input('What is the step size? ');
%if loop determines if dx is a vector or scalar
[r,c]=size(dx);
if (r>1)|| (c>1)
u=10*ones(size(dx)); %initialize u as a vector
for i=1:length(dx)
for j=dx(:,i):dx(:,i):10
u(:,i)=u(:,i)+u_prime(j-dx(:,i))*dx(:,i);
end
end
else
end
I have tried this:
[r,c]=size(dx);
if (r>1)|| (c>1)
u=10*ones(size(dx)); %initialize u as a vector
k=0;
for i=1:length(dx)
myvec=zeros(3,10/dx(:,i)+1);
for j=dx(:,i):dx(:,i):10
k=k+1;
u(:,i)=u(:,i)+u_prime(j-dx(:,i))*dx(:,i);
myvec(:,k)=u(:,i);
end
end
else
end
But myvec did not display properly. It had too many columns and the rows would only display the iterations for the last step size.
Risposte (1)
KSSV
il 28 Ago 2020
%initailze the derivative of u, u_prime, and the step size, dx
u_prime=@(x)(x^2+4);
% dx = input('What is the step size? ');
dx = [1. 0.5 0.1] ;
iwant = cell(length(dx),1) ;
for i = 1:length(dx)
x = dx(i):dx(i):10 ;
u = 10*ones(1,length(x)) ;
count = 0 ;
for j=dx(i):dx(i):10
count = count+1 ;
u(count)=u(count)+u_prime(j-dx(i))*dx(i);
end
iwant{i} = u;
end
iwant
Categorie
Scopri di più su MATLAB 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!