MATLAB Integrating Function with MATLAB - Solve & Plot

AI Thread Summary
The discussion centers on a user seeking assistance with integrating a piecewise function defined over specific intervals and plotting it alongside its derivative and the original function. The provided MATLAB code attempts to compute the integral but encounters an error due to incorrect indexing, where a vector is mistakenly assigned to a scalar variable. The solution involves correcting the code by using the appropriate index, changing 't' to 't(n)', and ensuring 't' is properly defined as a vector. Additionally, the user inquires about implementing an integration block in Simulink using M-code, specifically how to integrate a variable representing a derivative back to its original form. The conversation emphasizes the need for clarity in variable definitions and proper coding practices in MATLAB for successful execution.
Execute
Messages
2
Reaction score
0
Hi everyone, I have a problem in finding an integral of a function. I'm given the following function: x(t) = t + 1 (-1 <= t < o ); e^-t (0<= t <= 2); 0 (otherwise).I have to find the integral and plot it with its derivative and the given function.

Here is my code:
%Set up integral vector
u(1:1000) = 0;
%Find the integral
for n = 1:999;
if( (t(n)>= -1) & (t(n)<0) );
u(n) = 0.5.*(t.^2) + t;
end
if ( (t(n)>=0) & (t(n)<2) );
u(n) = -1.*(exp(-t));
end
if( (t(n)>2 ) )
u(n) = 1.*t;
end
end
subplot(3,1,3);
plot(t,u);

I get the following error when trying to run the code:
? In an assignment A(I) = B, the number of elements in B and
I must be the same.

Error in ==> tut1 at 32
u(n) = 0.5.*(t.^2) + t;
 
Physics news on Phys.org
Execute said:
Error in ==> tut1 at 32
u(n) = 0.5.*(t.^2) + t;

In these three lines
Code:
     u(n) = 0.5.*(t.^2) + t;
      u(n) = -1.*(exp(-t));
      u(n) = 1.*t;
you are trying to store a vector in a scalar's place. u(n) is a scalar and t is a vector, so change t to t(n) and you will be fine. Also, be sure to define t properly (don't see it in your code), e.g. t = linspace(-1,2,1000).
 
i have 1 question
how do i apply 1/s in simulink block to M-code,
for example
Xdot to X
in simulink, we just apply the 1/s(integration block).
so i just want to know, is it possible to integrate the Xdot to X in m code??
 

Similar threads

Replies
8
Views
2K
Replies
1
Views
2K
Replies
4
Views
1K
Replies
4
Views
4K
Replies
5
Views
2K
Replies
18
Views
4K
Replies
2
Views
3K
Back
Top