Why I am I getting a row

How should I fix it so that x1 can be a column
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, y0);
f = @(t) K / (1 + (K / x0 - 1) * exp(-1*r*t));
x1 = f(t);

Answers (1)

Thge easiest way is:
x1 = x1(:)
since this will force ‘x1’ to be a column vector regardless of its previous orientation.
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, x0);
f = @(t) K / (1 + (K / x0 - 1) * exp(-1*r*t));
x1 = f(t);
x1 = x1(:)
x1 = 45×1
0.5000 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.

4 Comments

Hi, I intend to input this column vector of t as well in order to not getting zeros. How should I fix it? Thank you!
I am not certain what you are asking.
In order to not produce any zeros, your ‘f(t)’ function should not produce them.
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, x0);
figure
plot(t,x)
grid
f = @(t) K / (1 + (K / x0 - 1) * exp(-1*r*t));
x1 = f(t);
x1 = x1(:)
x1 = 45×1
0.5000 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
.
For x1, I am using a different formula f = @(t) K / (1 + (K / x0 - 1) * exp(-1*r*t)). If you try to input index like f(1), f(2), it outputs a number perfectly well and it should not be 0. I think there is a problem of how this formula is defined.
I think there is a problem of how this formula is defined.
I agree. However since your coding for it is all that I have to work with, this is the best that I can do with it. Check to be certain that ‘r’ and ‘K’ have the correct values.
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, x0);
figure
plot(t, x, '.-')
grid
disp(t)
0 0.0670 0.1340 0.2010 0.2679 0.5179 0.7679 1.0179 1.2679 1.5179 1.7679 2.0179 2.2679 2.5179 2.7679 3.0179 3.2679 3.5179 3.7679 4.0179 4.2679 4.5179 4.7679 5.0179 5.2679 5.5179 5.7679 6.0179 6.2679 6.5179 6.7679 7.0179 7.2679 7.5179 7.7679 8.0179 8.2679 8.5179 8.7679 9.0179 9.2679 9.4510 9.6340 9.8170 10.0000
f = @(t) K / (1 + (K / x0 - 1) * exp(-1*r*t));
x1 = f(t);
x1 = x1(:);
disp(x1)
0.5000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
clearvars
syms K r t x(t) x0
DE = diff(x) == x*(1- x/K)
DE(t) = 
f = dsolve(DE, x(0) == x0)
f = 
f = simplify(f, 500)
f = 
fcn = matlabFunction(f)
fcn = function_handle with value:
@(K,t,x0)(K.*x0.*exp(t))./(K-x0+x0.*exp(t))
t = (0:10).';
K = 2;
x0 = 0.5;
fv = fcn(K,t,x0);
disp(fv)
0.5000 0.9507 1.4225 1.7401 1.8958 1.9604 1.9852 1.9945 1.9980 1.9993 1.9997
figure
plot(t, fv, '.-')
grid
xlabel('t')
ylabel('f(t)')
For what it is worth, the analytiic integration of your function does not closely resemble your anonymous function formulation of it.
.

Sign in to comment.

Tags

Asked:

on 21 Jan 2025

Commented:

on 21 Jan 2025

Community Treasure Hunt

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

Start Hunting!