Keep getting ERROR: Array indices must be positive integers or logical values for X(t)
Show older comments
I'm trying to write code that plots a graph of an oscillation system and keep getting the "Array indices must be positive integers or logical values." and can't figure out whats going wrong. Any help would be appreciated.
% Matlab Oscillation Assignment
clc; clear;
Vo = 0.6; %initial velocity
del = [0.05 0.1 0.2]; % Damping ratios
Wn = 5; % angular frequency rad/s
t = 0; % initial time
Xo = 0;
while t < 7
Wd = sqrt(1-((del.^2)*(Wn))) %damped angular frequency
Phase_Angle = atan((del.*Wn.*Xo+Vo)./Wd.*Xo) %phase
C = sqrt(Xo.^2+((del.*Wn.*Xo+Vo)./Wd).^2) %amplitude
X(t) = (C.*exp(1).^-del.*Wn.*t).*cos ((Wd.*t)-Phase_Angle) % equation for response of the system
t = t+1;
Xo = X(t);
grid on
plot(t,X(t),'-or')
hold on
end
2 Comments
Stephen23
on 17 Nov 2023
You have:
t = 0; % initial time
..
while t < 7
..
X(t) = ..
Is 0 a valid index (i.e. an integer >=1) ?
Dyuman Joshi
on 17 Nov 2023
Numerical indices in MATLAB start from 1, not 0.
As you are using t as a numerical index, it should be a positive integer.
Also, you are trying to assign a 1x3 array (the rhs to X(t)) to a 1x1 element (X(t)), which will give an error.
Since I do not know what you are trying to do, I can not provide you with any suggestions/solutions.
Answers (1)
Create ‘X’ as an anonymous function:
X = @(t,C,Wd,Phase_Angle) (C.*exp(1).^-del.*Wn.*t).*cos ((Wd.*t)-Phase_Angle) % equation for response of the system
and then call it in the loop —
% Matlab Oscillation Assignment
clc; clear;
Vo = 0.6; %initial velocity
del = [0.05 0.1 0.2]; % Damping ratios
Wn = 5; % angular frequency rad/s
t = 0; % initial time
Xo = 0;
X = @(t,C,Wd,Phase_Angle) (C.*exp(1).^-del.*Wn.*t).*cos ((Wd.*t)-Phase_Angle); % equation for response of the system
while t < 7
Wd = sqrt(1-((del.^2)*(Wn))); %damped angular frequency
Phase_Angle = atan((del.*Wn.*Xo+Vo)./Wd.*Xo); %phase
C = sqrt(Xo.^2+((del.*Wn.*Xo+Vo)./Wd).^2); %amplitude
t = t+1;
Xo = X(t,C,Wd,Phase_Angle);
grid on
plot(t,Xo,'-or')
hold on
end
This works, however there are obviously still problems. I leave those to you to resolve.
.
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!