Vector with symbolic variable

1 view (last 30 days)
Lilted
Lilted on 4 May 2024
Commented: Lilted on 7 May 2024
I have created a 8x1 sym (vector?) called psi and a 1x1000 double (vector?) called time. When I try to plug in a value from the double into the psi I use the syntax:
psi_eval = psi(time(2));
since this is the way I would have done it in python, however it does not work. I get an error saying:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 909)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in BachelorThesis (line 65)
psi_eval = psi(time(2));
The array index I have given is a positive value so I don't understand the error I get. What am I doing wrong?

Accepted Answer

Steven Lord
Steven Lord on 4 May 2024
If you have a symbolic variable that contains a function of another symbolic variable and you want to substitute values for that "inner" symbolic variable, use the subs function.
syms t
y = t.^2;
subs(y, t, 1:5)
ans = 
If it's a symbolic function then you can use parentheses like you tried.
syms x(t)
x(t) = t.^3;
x(1:5)
ans = 

More Answers (2)

Walter Roberson
Walter Roberson on 4 May 2024
Edited: Walter Roberson on 4 May 2024
Your time vector contains at least one value that has a fraction or is not a positive value.
For example, your time vector might start from 0, or might increment by 1/10th of a second.
mask = find(time ~= floor(time) | time <= 0);
if isempty(mask)
fprintf('times check out okay!\n');
else
fprintf('invalid times!\n');
disp(compose("index %03d, value %g", mask(:), time(mask)));
end

Torsten
Torsten on 4 May 2024
Moved: Torsten on 4 May 2024
Works for me.
psi = sym('psi',[8 1]);
t = 1:1000;
psi(t(5))
ans = 
  2 Comments
Lilted
Lilted on 4 May 2024
I don't find that helpful. I have 8x1 sym object, the elements are something that depends on t. When I write:
psi_eval = psi(time(2));
I want the code to plug in the second value in the list time into my sym object and evaluate what it will be.
Paul
Paul on 4 May 2024
Why not show a simple, but complete, example that makes shows the full code, in partcular the defintion of psi, and clearly shows what you're trying to do? As it stands, we can only guess. Maybe something like this:
syms t
psi = [t;2*t];
time = rand(1,2000);
subs(psi,t,time(2))
ans = 
vpa(ans)
ans = 
[time(2);2*time(2)]
ans = 2x1
0.2286 0.4573
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!