Appending a calculated value during each iteration of a for loop
14 views (last 30 days)
Catherine Zdunek on 16 Mar 2021
Hi! I am trying to use a for loop in a function code to append a calculated value to a vector for each iteration of the loop. For some context, the code I am writing is for calculating eigen values and eigen vectors for a system of ODEs. I am trying to calculate the coefficent values (called eigen_factors in my code) for each value of time, t, and then store all of those values in a vector, using the for loop. Whenever I call my function in a separate scricpt, it says that the variable eigen_factors is not defined in the function. I'm not sure why my function is not running the for loop, so please let me know if you have any suggestions!
Before the for loop, I have my attempt at preallocation. As of now, I have it with a % in front because when I kept in in the fucntion, the output value for eigen_factors would be that preallocation value. I'm not sure if I did that correctly, but my main problem here is just getting the for loop to run.
I had also tried calculating the coefficent values separtely within the for loop and then storing it in the eigen_factors vector, but I was not able to get that to work either.
Here is my code for the function of interest.
function [x, u, lambda, v, eigen_factors] = eigen_diffuse(sigmoid_ic, tspan, n)
%tspan_size=size(tspan); %part of preallocation attempt
%eigen_factors=zeros(tspan_size); %preallocation (or my attempt at that lol)
%this is where the problem begins to occur
%rest of code (no problems here)
David K. on 16 Mar 2021
I can't see right away what the dimension of
is expected to be so I am just going to put out answers for various situations. The main problem looks to be that you are not indexing eigen_factors in the loop.
eigen_factors(i)=[c_k.*exp(lambda*tspan(i))]; % change in loop
eigen_factors = zeros(n,length(tspan)); % Preallocation
eigen_factors = zeros(length(tspan),n); % Preallocation
eigen_factors = zeros(n,m,length(tspan)); % Preallocation