MATLAB Answers

Appending a calculated value during each iteration of a for loop

2 views (last 30 days)
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
for i=1:tspan
%rest of code (no problems here)
Thank you!!!
Catherine Zdunek
Catherine Zdunek on 17 Mar 2021
Thank you! I wasn't sure if those were necessary, so good to know for the future also!

Sign in to comment.

Accepted Answer

David K.
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.
Case: 1x1
eigen_factors(i)=[c_k.*exp(lambda*tspan(i))]; % change in loop
Case: 1xn
eigen_factors = zeros(n,length(tspan)); % Preallocation
Case: nx1
eigen_factors = zeros(length(tspan),n); % Preallocation
Case: nxm
eigen_factors = zeros(n,m,length(tspan)); % Preallocation

More Answers (0)

Community Treasure Hunt

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

Start Hunting!