This subreddit is back open to the public. You can post your Scilab queries here. It may take a while to breathe life back into the subreddit so get the word out. I'll will be working on the wiki to get some Scilab support information out there and some links to the discord site.
I would like to perform a closed loop simulation with PID control; but unfortunately it is not working, a graph of an infinite line appears, I probably configured something wrong. It was supposed to be like this other graph from colab. If anyone can help me, I thank you in advance.
Hi all! How many of you use xcos and scilab for testing control strategies to be implemented in embedded systems? I mean real time discrete control simulations and even custom C code blocks for control validation.
I know there are Commercial solutions for power electronics, vehicle dynamics, robotics, etc. but a "free for commercial purposes" licensing makes scilab and xcos super interesting for small companies that can not afford expensive Simulink (Matlab) or Simba (Python) simulation environments.
Did I discovered the paradise of control engineers?
outputString = strcat(['3d result = ', string(result)]);
disp(outputString);
I understood that v had to be a single number how to get it was the trick. It would have been really nice to have an example like this one in their documentation.
Go ahead and roast me if you thought was blatantly obvious!
Hello, I'm going through a Scilab course on Udemy, but it is too brief. I don't know where to go to continue learning about the program after I'm done with this course. Until now my only option would be searching the scilab manual, keyword for keyword.
Background: 3rd year engineering student, know basic principles of some very basic languages and Matlab.
Note some extra stuff not part of the Numerical Analysis Course: I've added some determinate tracking calculation throughout the program just to show how the partial pivoting and decompositions affect the determinate value. I'm currently refreshing my Linear Algebra stuff and I'm on determinants and row operation influences.
I also added the use of the "lu" function in SciLab and how to get the solution vector using the lu function result and rref function techniques. I had some disappointment that the lusolve command is only for solving sparse matrices.
As I mentioned that I would add some SciLab code I generated while doing a refresher on Numerical Computation (and gave me an opportunity to learn SciLab less the XCOS stuff).
The YouTube channel is referenced in the second line of the program just remember strip off the "//" (// is making it a comment line in SciLab) before the https://...
"Solution from back substitution in L and U x3 = "
"Solution from the l-u decomposition ="
1.0000000
2.0000000
1.0000000
//Lecture 4.3: LU Decomposition and Partial Pivoting
//https://www.youtube.com/watch?v=smsE7iOlNj4&t=17s&ab_channel=MATLABProgrammingforNumericalComputation
//
// x1+ x2+ x3 = 4
//2*x1+ x2+3*x3 = 7
//3*x1+4*x2-2*x3 = 9
//Using Matlab's powerful Linear Algebra:
clc
A = [1,1,1;3,4,-2;2,1,3];
//A = [3,4,-2;1,1,1;2,1,3]; //Already "pivoted" matrix form
//A=[-3 2 6;5 -1 5;10 -7 0]; //Just another matrix to play with...
disp("A = ", A);
disp("determinate of A =", det(A));
//We show how the determinant is
// affected with these calculations too.
b = [4;9;7];
//b = [9;4;7]; //goes along with the already "pivoted" A matrix
disp("b = ", b);
Ac=[A,b];
disp("Augmented Matrix A:b =",Ac)
[n,m]=size(Ac);
//disp("n,m "+string(n)+" and "+string(m));
L=eye(A);
//disp("L =",L);
x1 = A\b;
disp("Solution to Ax =b x1 =",x1);
//Calculate L matrix using Gauss Elimination
// We're going to add Partial Pivoting where
// we select the largest element in row 1 and exchange
// that equation with the 1st row.
nswaps = 0;
for k = 1:1:n
// number of row swaps
for i = k:1:n
if (abs(Ac(i,k))>abs(Ac(k,k))) then
temp = 0
nswaps = nswaps + 1
for j=1:1:m
temp = Ac(k,j)
Ac(k,j)=Ac(i,j)
Ac(i,j)=temp
end
// disp("Ac =",Ac);
end
end
end
disp("Ac pivot =",Ac);
Ad = Ac(1:3,1:3);
disp("number of row swaps =", nswaps)
disp("determinate of the pivoted A =", (-1)^nswaps*det(Ad));
//We did 'nswaps' row swaps and everytime we do a row swap, it changes
//the sign of the determinant. We are doing LU decomposition on the
//partial pivoted matrix not the original matrix. We've coded in the
//sign change so it should show no difference in the determinant on
//the final determinant calculation.
//Calculate L matrix
for i = 1:1:n
for j = i+1:1:n
alpha = Ac(j,i)/Ac(i,i);
L(j,i)=alpha;
// disp("alpha ="+string(alpha));
//Rj = Rj-alphai,j*Ri where alphai,j = A(j,i)/A(i,i)
Ac(j,:)=Ac(j,:)-alpha.*Ac(i,:);
// disp("Ac = ",Ac);
end
end
U = Ac(1:n,1:n);
disp("L =",L,"U =",U);
disp("determinant of L =" ,det(L));
disp("determinant of U =", det(U));
disp("determinant of L*U", (-1)^nswaps*det(L*U),"which is the same as determinate A");
//should show no change in determinant since we've only added or subtracted
//row operations with nswaps row swaps but no multiplication)
//LU decomposition
[l,u]=lu(A)
//note we're doing the lu decomposition on the original
//matrix
disp("l =",l);
disp("u =",u);
disp("determinant of l =" ,det(l));
disp("determinant of u =", det(u));
disp("determinant of l*u", det(l*u),"which is the same as determinate A");
//note: lu command doesn't change determinant when done on the original
//matrix
//Backsubstitution
x3 =zeros(m,1);
//need 1 longer in vector so formula works
for i = n:-1:1
x3(i)= (Ac(i,$)-(Ac(i,i+1:$)*x3(i+1:$)))/Ac(i,i);
end
disp("Solution from back substitution in L and U x3 = ",x3(1:n))
//Solve using the lu decomposition results
//l*y = b and u*x4 = y and we're going to use the function rref()
//solve the system equations
Af =
rref
([l b])
//row reduce until we get the y vector in the last column
y = Af(1:$,$)
// pick off the last column
Ag =
rref
([u y])
//row reduce until we get the x4 solution in the last column
x4 = Ag(1:$,$)
// pick off the last column
disp("Solution from the l-u decomposition =", x4)
//One more note - there is a Scilab function lusolve - this is for sparse
//matrices - it chokes on these non-sparse matrices. Do not attempt to use.
//
Subject - Simultaneous Equations via Several Methods (Matrix Inversion, the backslash command, Gaussian Elimination, and row reduced echelon command).
As I mentioned that I would add some SciLab code I generated while doing a refresher on Numerical Computation (and gave me an opportunity to learn SciLab less the XCOS stuff).
The YouTube channel is referenced in the second line of the program just remember strip off the "//" (// is making it a comment line in SciLab) before the https://...
Subject - More on Numerical Integration Techniques
I mentioned that I would add some SciLab code I generated while doing a refresher on Numerical Computation (and gave me an opportunity to learn SciLab less the XCOS stuff).
The YouTube channel is referenced in the second line of the program just remember strip off the "//" (// is making it a comment line in SciLab) before the https://...
"The integral of 2-x+ln(x) from 1 to 2 with step size 0.025 is ... "
"True Value = 0.8862944"
"Trap Value = 0.8862683 with Error = 0.000026"
"Simp Value = 0.8862944 with Error = 3.794D-09"
"Execution done."
Code:
//Numerical Integration
//Lec 3.4 Newton-Cotes Integration Formulae
//https://www.youtube.com/watch?v=tByDeErG0Ic&t=13s&ab_channel=MATLABProgrammingforNumericalComputation
//
// Integration is area under a curve
// Single Variable application
// Trapezoid Rule -> Area = h*(f(x+h)+f(x))/2 = 2 points
// Truncation Error - Order h^3
// Simpson's 1/3rd Rule -> 3 point fit
// area for "x to x+2h" = h/3*(f(x)+4*f(x+h)+f(x+2h))
// Truncation Error - Order h^5
// Simpson's 3/8th Rule -> 4 point fit
// area for "x to x+3h" = 3h/8*(f(x)+3*f(x+h)+3*f(x+2h)+f(x+3h))
// Truncation Error - Order h^5
// Let's do an example
// integrate f(x)= 2 - x + ln(x)
// true value = 2*x - 0.5*x^2 + (x*ln(x)-x)
// simplifying = x - x^2/2 + x*ln(x)
// compare Trap and 1/3 Simpson rules
function result =f(x)
result = 2-x+log(x);
endfunction
a = 1;
b = 2;
//number of steps
n = 40;
//n needs to be even!
h = (b-a)/n;
disp("The integral of 2-x+ln(x) from "+ string(a)+" to "+string(b)+" with step size "+string(h)+" is ... ")
TruVal = (b-b^2/2+b*log(b))-(a-a^2/2+a*log(a));
disp("True Value = "+string(TruVal));
Trap_area = 0.;
Simp_area = 0.;
for i = 1:1:n;
x = a + h.*(i-1);
f1 = f(x);
f2 = f(x+h);
areaT = h*(f2+f1)/2;
Trap_area = Trap_area + areaT;
end
errT = abs(TruVal - Trap_area);
disp("Trap Value = "+string(Trap_area)+" with Error = "+string(errT));
for i = 1:1:n/2;
x = a + (2*h).*(i-1);
f1 = f(x);
f2 = f(x+h);
f3 = f(x+(2*h));
areaS = h/3*(f1+4*f2+f3);
Simp_area = Simp_area + areaS;
end
errS = abs(TruVal - Simp_area);
disp("Simp Value = "+string(Simp_area)+" with Error = "+string(errS));
Can someone please help me. I don't know what to do. I just received a chromebook running in Linux. I'm stuck. I just downloaded the file from the site and it's a
.tar.xz
Now what do I do? If I click the file, it doesn't say download or something.
I am relatively new to fedora (have used ubuntu/debian before for testing). I am trying to get Scilab to launch but I am having issues. Just to make sure, the fedora image in running inside a container and currently is in root (no users defined yet). I have installed all the requisite packages I need.
The output I get is as followed
[root@localhost ~]# scilab
Could not access to the Main Scilab Class:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.scilab.modules.localization.Messages.gettext(Unknown Source)
at org.scilab.modules.commons.xml.XConfiguration.<clinit>(Unknown Source)
at org.scilab.modules.core.Scilab.<clinit>(Unknown Source)
Caused by: java.lang.NullPointerException
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1847)
at java.lang.Runtime.loadLibrary0(Runtime.java:871)
at java.lang.System.loadLibrary(System.java:1124)
at org.scilab.modules.localization.MessagesJNI.<clinit>(Unknown Source)
... 3 more
Scilab cannot create Scilab Java Main-Class (we have not been able to find the main Scilab class. Check if the Scilab and thirdparty packages are available).
[root@localhost ~]#
The output makes it seem JAVA is mising, but I have both openjdk1.8 and openjdk11 and latest openjdk installed. Switching between them doesn't change anything. whereis java and java -version all work as well as I checked premissions using ls -l dir and they all have the -xwrxr (makes sense since I am root atm). scilab-cli works fine. I cannot understand if its driver issue either, because I already have software 3D acceleration and FreeCAD, gmsh, paraview, blender and even octave work.
I don't know much about Java debugging so I am hoping I can get some pointers.
I am a beginner in scilab. I was trying to write certain functions, when accidentally i closed the variable browser. Now I have to manually open it from applications as a separate window which earlier was already embedded below my file browser. Any help on how to reverse it?
clear, close, clc
disp("Data-Driven Science and Engineering -PCA Ovarian Cancer Example",string(datetime()))
//Section 1.5 Principal Component Analysis
//github databook_matlab code file
//https://github.com/dynamicslab/databook_matlab/blob/master/CH01/CH01_SEC05_2_OvarianCancer.m
//location of the OvarianCancer.mat file
//https://www.mathworks.com/matlabcentral/answers/1955269-function-for-visualisation-of-raw-data-ovarian-cancer
//load observation data - complete path
loadmatfile("C:\Users\MattheW\Documents\eBooks\ScILabNotes\DataScience\CODE\CH01\OvarianCancer.mat","-mat")
obs = X'
//Since the OvarianCancer.mat file did not have the "grp" data with
// it, I need to generate it based upon what he verbalized"
// First 113 were "Cancer" and the rest of the 216 were "Normal"
grp = cell(1,216); // Note: I've hard coded the length of Y into grp!!!
for i = 1:113
grp{i} = 'Cancer';
end
for i = 114:216
grp{i} = 'Normal';
end
// I could save grp and Y as grp and obs respectively OvarianCancer.mat
// but not today!
[U,S,V] = svd(obs,'e');
scf(0)
clf
subplot(1,2,1)
semilogy(diag(S),'k-o','thickness',1.5)
//set(gca,'FontSize',13),
//axis tight
xgrid
xlabel('r')
ylabel('Singular Value sigma_r')
subplot(1,2,2)
plot(cumsum(diag(S))./sum(diag(S)),'k-o','thickness',1.5)
//set(gca,'FontSize',13), axis tight,
xgrid
xlabel('r')
ylabel('Cumulative Energy')
//set(gcf,'Position',[100 100 600 250])
scf(1)
clf
for i = 1:size(obs,1)
x = V(:,1)'*obs(i,:)';
y = V(:,2)'*obs(i,:)';
z = V(:,3)'*obs(i,:)';
if (grp{i}=='Cancer')
scatter3d(x,y,z,"markerFaceColor","red");
else
scatter3d(x,y,z,"markerFaceColor","blue");
end
end
xlabel('PCA 1')
ylabel('PCA 2 [Cancer - Red Dots Normal - Blue Dots]')
zlabel('PCA 3')
gca().rotation_angles =[85,25];
xgrid
We're starting a new series off of the Steve Brunton's Data-Driven Science and Engineering Series. He's definitely one of my favorite instructors when it comes to numerical and data analysis. First topic of the first short course series is Singular Value Decomposition (SVD). For this first example, it will be using the Image compression as an applied example.
To follow the series,
(As a motivator, I wish I'd had this method in my "Engineering Toolbox" since this technique helps one "sort the wheat from the chaff" when it comes to data reduction. I just never came across it in this form. I've done "Design of Experiments", produced "Statistical Models" and used techniques to figure out "what was important and what was not" but this SVD technique is very scalable.)
2) I do suggest you download the book and read the pertinent sections.
3) Download the data used for the short course. See below for location of the data.
4) For the Scilab code below to work, you'll need to use the Atoms Module Manager, navigate to Image Processing and install the Image Processing and Computer Vision Toolbox (IPCV 4.5.0.2).
5) I'm using Scilab 26.1.0 but have run this successfully on version 26.0.0.
I'm not sure how much coverage SciLab provides for this course but we'll see as we go along.
====================================
These lectures (videos) follow Chapter 1 from the book (freely available in electronic form): "Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control" by Brunton and Kutz
Data and Python and MATLAB Native Code athttps://databookuw.com/ Note: links to Matlab Code.zip + Data.zip on Main Page
Steve Brunton already has two other short courses on Fourier Transforms and Sparsity & Compression which might be material for future series.
Output: None - Graphical Only
Plots:
Code:
/* Start Block Comment
//Singular Value Decomposition Overview
//https://www.youtube.com/watch?v=gXbThCXjZFM&list=PLMrJAkhIeNNSVjnsviglFoY2nXildDCcv&index=1
//These lectures follow Chapter 1 from:
//"Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control" by Brunton and Kutz
//Amazon: https://www.amazon.com/Data-Driven-Sc... //If you want hardcopy book.
//Book Website: http://databookuw.com //Free Electronic Web-based Version
//Chapters available at: http://databookuw.com/databook.pdf //Free Electronic Version
//For Free Electronic Complete Textbook "FREE PDF for 2ND EDITION OF OUR BOOK!!!" https://x.com/eigensteve/status/1718004606901666063
//Brunton Website: http://eigensteve.com
//Singular Value Decomposition: Mathematical Overview Short Lecture 2
//https://www.youtube.com/watch?v=nbBvuuNVfco&list=PLMrJAkhIeNNSVjnsviglFoY2nXildDCcv&index=2
//Singular Value Decomposition: Matrix Approximation Short Lecture 3
//https://www.youtube.com/watch?v=xy3QyyhiuY4&list=PLMrJAkhIeNNSVjnsviglFoY2nXildDCcv&index=3
//Singular Value Decomposition: Dominant Correlations Short Lecture 4
//https://www.youtube.com/watch?v=xy3QyyhiuY4&list=PLMrJAkhIeNNSVjnsviglFoY2nXildDCcv&index=4
//He discusses getting code and data files in this fifth lecture
//https://www.youtube.com/watch?v=QQ8vxj-9OfQ&list=PLMrJAkhIeNNSVjnsviglFoY2nXildDCcv&index=5
//Data and Python and MATLAB Native Code at https://databookuw.com/
//links to Code.zip + Data.zip on Main Page
*/ //End of Block Comment
clear, close, clc
disp("Data-Driven Science and Engineering - Singular Value Decomposition Image Processing Example ",string(datetime()))
//Need to load this atoms module into SciLab for imread, imshow, rgb2gray
atomsLoad("IPCV") //Once loaded into Scilab, this command line is unnecessary
//Use full file path to your unzipped data file...
A=imread('C:/Users/Matthew/Documents/eBooks/ScILabNotes/SVD_PCA_Course/DATA/dog.jpg');
X=double(rgb2gray(A)); // Convert RBG->gray, 256 bit->double.
nx = size(X,1); ny = size(X,2);
scf()
clf
subplot(2,2,1)
imshow(uint8(X));
title('Original in Gray Scale');
[U,S,V] = svd(X);
plotind=2;
for r=[5 20 100]; // Truncation value
Xapprox = U(:,1:r)*S(1:r,1:r)*V(:,1:r)';
// Approx. image
subplot(2,2,plotind)
plotind = plotind+1;
imshow(uint8(Xapprox))
title(['r=', msprintf('%d',r),', ',msprintf('%2.2f',100*r*(nx+ny)/(nx*ny)),' % storage']);
end
// f_ch01_ex02_2
scf();
clf;
subplot(1,2,1), semilogy(diag(S),'k')
xgrid
xlabel('r')
ylabel('Singular Value sigma_r')
subplot(1,2,2), plot(cumsum(diag(S))/sum(diag(S)),'k')
xgrid
xlabel('r')
ylabel('Cumulative Energy')
In this edition we look at solving Boundary Value Problems with Nonlinear Equation and one with a mixed boundary (parameter is held at a value in one location and it's derivative is held at a value at another location.
Note: The program has two major blocks and in it's current configuration (the first major block (the Nonlinear Example) runs and the second example (the Mixed Boundary Condition Example) is "block commented" out.
Link to the specific lecture (note the urls cover the same material) and one might find it useful to use the NPTEL Link:
//Lecture 10.4: Extensions of ODE-BVP
//https://www.youtube.com/watch?v=chChbuP-hRk&ab_channel=NPTEL-NOCIITM
//https://nptel.ac.in/courses/103106118
//
disp("Extensions of ODE-BVP",string(
datetime
()))
//
// Extension 1) Non linear equation
// Extension 2) Mixed Boundary Condition
//
//Boundary Value Problems
//Example Heated Fin/Rod
//d2T/dx^2=gamma1*(T-25);
//
//Two easy causes of non-linearity are:
// add Radiation to the right hand side.
// heat loss = sigma1*epsilon*((T+273)^4-(Ta+273)^4))
//
// gamma1 is a function of T so convection term is
// gamma1(T)(T-25) where typically gamma1 = gamma0*T^0.75
// in our example, we use gamma1= gamma0*T^1 due
// numerical issues using 0.75 (which I do not want to investigate
// at this time).
//
// so in our case "ff = gamma1*(u(1)-Ta)"
// becomes "ff = gamma0*u(1)*(u(1)-Ta)"
// and "dff = [gamma0*(2*u(1)-Ta),0];"
// using gamma0 = 0.04 to keep solution close to prior gamma1 of 4
//
// Mixed Boundary Condition
// 1) Dirichlet T(0)=100, T'(1)=b(T)
// 2) Nuemann T'= some value
// 3) Mixed Phi(T,T')=0
//
// First Case Non-Linear Function...
// T at wall = 100 C
// T at end (x=1) = 25 C
//
// 0 = k*d2T/dx^2-h*av*(T-Ta)
// where k = thermal conductivity of rod
// h = convection coefficient of conditions
// av = surface area of the rod
// Ta = Temperature of surrounding atmospere
// d2T/dx^2 = (h*av/k)*(T-Ta);
// d2T/dx^2 = gamma1*(T-Ta);
//
//Boundary Condition 1: 0 = g1(ya,yb)=> T(x=0)-100 = 0
//B C 2: T(x=1)-25 = 0
// The external functions
// These functions are called by the solver with zu=[u(x);u'(x);u''(x);u'''(x)]
// - The function which computes the right hand side of the differential equation
funcprot(0);
function ff=
f
(x, u)
//Define Constants
Ta = 25;
gamma0=0.04;
ff = gamma0.*u(1).*(u(1)-Ta);//right hand side of the differential equation
endfunction
// - The function which computes the derivative of f with respect to u
function dff=
df
(x, u)
Ta =25
gamma0=.04;
dff = [0, gamma0.*(2.*u(1)-Ta)];
endfunction
function [gg]=
g
(i, u)
gg=[u(1)-100,u(1)-25];//Boundary Value Conditions
// T(x=0)=100, T(x=1)=25 ,u(1)=T, u(2)=dT/dx, u(n+1)=dnT/dx^n (but not
// used) since order is only 2....
gg=gg(i);
endfunction
function [dgg]=
dg
(i, u)
dgg = [1,0;1,0] //must be consistent with the boundary conditions
//set in subroutine g so if you have two boundary conditions on
// u(1), it is [1,0;1,0]...if you have one condition on u(1) at the first
// location and u(2) on the other, it needs to be [1,0;0,1] with gg
// having the u(1) condition first. If the u(1) condition is at the second
// position instead and the first has a u(2), it would look
// like [0,1;1,0]...
//
dgg=dgg(i,:);
endfunction
function [u0, du0]=
guess
(x)
u0=100;
du0=-100;
endfunction
//
n = 1; //One differential equation
m = 2;// Second order differential equation
xL=0;
xR = 1;
Dx=0.05;
x = [xL:Dx:xR];
fixpnt = [];
zeta = [xL,xR];
ipar=zeros(1,11);
ipar(3)=1;
ipar(4)=2;
ipar(5)= 10000;
ipar(6) = 2000;
ipar(7)=1;
ltol =[1,2];
tol = [1e-5,1e-5];
u = bvode(x,n,m,xL,xR,zeta,ipar,ltol,tol,fixpnt,
f
,
df
,
g
,
dg
,
guess
);
FiniteDifferenceMethodSoln = [
100.000
93.3411
87.3202
81.8434
76.8318
72.2185
67.9461
63.9656
60.2343
56.7153
53.3761
50.1884
47.1271
44.1701
41.2977
38.4927
35.7396
33.0249
30.3367
27.6647
25.0000
];
FD_dTdx = [
-133.1775
-126.7985
-114.9776
-104.8836
-96.2490
-88.8566
-82.5285
-77.1180
-72.5033
-68.5822
-65.2689
-62.4901
-60.1831
-58.2936
-56.7738
-55.5814
-54.6782
-54.0293
-53.6024
-53.3668
-53.2931
]
allData = [x' u' FiniteDifferenceMethodSoln FD_dTdx]
disp("Pos x Temp T TempGrad FiniteDiff FiniteDiff_dTdx", allData);
//Plotting
scf
(0);
clf
;
//axis y1
c = color("black")
c1 = color("blue")
c2 = color("green")
c3 = color("purple")
plot2d(x,u(1,:),style=c3) //,'x','y(x)',"Nonlinear Function")
h1=
gca
();
plot2d(x,FiniteDifferenceMethodSoln,style=c1);//black =, blue = 2, green =3, cyan = 4, red = 5 ;//Commented out for last example
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$X$","FontSize",3)
ylabel
("$T(x) $","FontSize",3);
title
("$\textbf{Nonlinear Function}$","FontSize",4);
legend
("BVODE","Finite Difference Values",3)
xgrid;
scf
(1);
clf
;
c = color("black")
c1 = color("blue")
c2 = color("green")
c3 = color("purple")
plot2d(x,u(2,:),style=c3)//,'x','dy/dx',"BVODE 2nd order solution")
plot2d(x,FD_dTdx,style=c1);//black =, blue = 2, green =3, cyan = 4, red = 5 ;//Commented out for last example
h1=
gca
();
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$X$","FontSize",3)
ylabel
("$dT/dx$","FontSize",3);
title
("$\textbf{Nonlinear Function}$","FontSize",4);
legend
("BVODE","Finite Difference Values",4)
xgrid
//End of First Example Block
/*
//
// Second Case Mixed Boundary...
//
//Boundary Value Problems
//Example Heated Fin/Rod
//d2T/dx^2=gamma*(T-25);
// T at wall = 100 C
// replace "T at end (x=1) = 25 C" with "dT/dx(x=1) = 0"
// so end is insulated
//
// 0 = k*d2T/dx^2-h*av*(T-Ta)
// where k = thermal conductivity of rod
// h = convection coefficient of conditions
// av = surface area of the rod
// Ta = Temperature of surrounding atmospere
// d2T/dx^2 = (h*av/k)*(T-Ta);
// d2T/dx^2 = gamma1*(T-Ta);
//
//Boundary Condition 1: 0 = g1(ya,yb)=> T(x=0)-100 = 0
//B C 2: dT/dx(x=1) = 0
// The external functions
// These functions are called by the solver with zu=[u(x);u'(x);u''(x);u'''(x)]
// - The function which computes the right hand side of the differential equation
funcprot(0);
function ff=
f
(x, u)
//Define Constants
Ta = 25;
gamma1=4;
ff = gamma1*(u(1)-Ta);//right hand side of the differential equation
endfunction
// - The function which computes the derivative of f with respect to u
function dff=
df
(x, u)
gamma1=4;
dff = [gamma1,0];
endfunction
function [gg]=
g
(i, u)
//change gg=[u(1)-100,u(2)-25];//Boundary Value Conditions
// to
gg=[u(1)-100,u(2)-0];//Boundary Value Conditions
// T(x=0)=100, T'(x=1)= 0 (Insulated End)
//
// T(x=0)=100, T(x=1)=25 ,u(1)=T, u(2)=dT/dx, u(n+1)=dnT/dx^n (but not
// used) since order is only 2....
gg=gg(i);
endfunction
function [dgg]=
dg
(i, u)
// change dgg = [1,0;1,0]
//to
dgg = [1,0;0,1]
//must be consistent with the boundary conditions
//set in subroutine g so if you have two boundary conditions on
// u(1), it is [1,0;1,0]...if you have one condition on u(1) at the first
// location and u(2) on the other, it needs to be [1,0;0,1] with gg
// having the u(1) condition first. If the u(1) condition is at the second // position instead and the first has a u(2), it would look
// like [0,1;1,0]...
//
dgg=dgg(i,:);
endfunction
function [u0, du0]=
guess
(x)
u0=100;
du0=-100;
endfunction
//
n = 1; //One differential equation
m = 2;// Second order differential equation
xL=0;
xR = 1;
Dx=0.1;
x = [xL:Dx:xR];
fixpnt = [];
zeta = [xL,xR];
ipar=zeros(1,11);
ipar(3)=1;
ipar(4)=2;
ipar(5)= 10000;
ipar(6) = 2000;
ipar(7)=1;
ltol =[1,2];
tol = [1e-8,1e-8];
u = bvode(x,n,m,xL,xR,zeta,ipar,ltol,tol,fixpnt,
f
,
df
,
g
,
dg
,
guess
);
//Analytical Answer (Insulated End)
T = 25+75*cosh(2*(1-x))/cosh(2);
dTdx = 150.*cosh(2.*x).*(tanh(2.*x)-tanh(2));
allData = [x' u' T' dTdx']
disp("Pos x Temp T TempGrad Analytical Analytical Derivative", allData);
//Plotting
scf
(0);
clf
;
//axis y1
c = color("black")
c1 = color("blue")
c2 = color("green")
c3 = color("purple")
plot2d(x,u(1,:),style=c1) //,'x','y(x)',"Example Heated Fin/Rod with Insulated End")
h1=
gca
();
plot2d(x,T+1,style=c3);//black =, blue = 2, green =3, cyan = 4, red = 5 ;//Commented out for last example
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$X$","FontSize",3)
ylabel
("$T(x) $","FontSize",3);
title
("$\textbf{Example\ Heated\ Fin/Rod\ with\ Insulated\ End}$","FontSize",4);
legend
("BVODE","Analytical Values+0.01",2)
xgrid;
scf
(1);
clf
;
c = color("black")
c1 = color("blue")
c2 = color("green")
c3 = color("purple")
plot2d(x,u(2,:),style=c1)//,'x','dy/dx',"Example Heated Fin/Rod with Insulated End")
plot2d(x,dTdx'+1,style=c3);//black =, blue = 2, green =3, cyan = 4, red = 5 ;//Commented out for last example
h1=
gca
();
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$X$","FontSize",3)
ylabel
("$dT/dx$","FontSize",3);
title
("$\textbf{Example\ Heated\ Fin/Rod\ with\ Insulated\ End}$","FontSize",4);
legend
("BVODE","Analytical Values+1",4)
xgrid
*/
Hey everyone! I'm u/mrhoa31103, the moderator of r/scilab a recovering subreddit from the great Apollo incident exodus.
This is our new home for all things related to Scilab. We're excited to have you join us!
What to Post Post anything that you think the community would find interesting, helpful, or inspiring. Feel free to share your thoughts, photos, or questions about Scilab and its applications.
Community Vibe We're all about being friendly, constructive, and inclusive. Let's build a space where everyone feels comfortable sharing and connecting. I'm running kind of a blog on Scilab programs so people can see full up working programs but do not feel your posts have to live up those formats. If you have a quick question, "how do you do this or that?" or found a neat application, share it.
Thanks for being part of the community. Together, let's make r/scilab amazing.
In this edition we solve the second order, constant coefficient (the mass, spring, damper problem) ODE using a pair of first order ODE's as a system of ODEs.
I've included some additional code to create the "Phase Portrait" of the same problem. The additional code was not part of the original course but covered in an advanced Engineering Mathematics course ME564 by Steve Brunton.
//Ordinary Differential Equations Initial Value Problems
//Lec 8.1 Solving Multi-Variable ODE Methods
//https://www.youtube.com/watch?v=i5Ton-G9zNs&ab_channel=MATLABProgrammingforNumericalComputation
//
//
disp("Ordinary Differential Equations- Multi-Variable ODE Methods of Integration",string(
datetime
()))
//
// model mass-spring-damper
// m*d^2x/dt^2 + c*dx/dt +kx = 0
// u/x(0)=1
//
// create 2 - first order equations
// d^2/dt^2 = dv/dt where v = velocity
// m*dv/dt +c*v + kx = 0
// v = dx/dt where x = displacement
//
// dx/dt = v x(0)=1
// dv/dt = -(c*v+k*x)/m v(0)=0
//
// output vector y =[x;v]
// derivative vector = [v; -(c*v+k*x)/m]
//
function [results]=
derivativeVector
(t, y);
//constants of the system
c=5;
k=15;
m=10;
//extraction of variables
x = y(1);
v = y(2);
results(1,1)=v;
results(2,1)=-(c*v+k*x)/m
endfunction
y0=[1;0];
t0 = 0;
n = 100;
t = linspace(0,20,n)';
//y = ode("rkf",y0,t0,t,derivativeVector)
y = ode("adams",y0,t0,t,
derivativeVector
)
// Other types of integration "adams","stiff","rk","rkf","fix","discrete"
// and "root"
// Everything works but "discrete" for this problem
// discrete is a sampling routine!!
y = y';//Transform from row vectors to column vectors
x_vector =y(:,1);
v_vector=y(:,2);
output = [t,v_vector,x_vector]
disp("time velocity displacement",output)
// Note: Very accurate and uses Runge-Kutta 4,5 uses
// variable step size and just reports out at time t vector
//
// Other types of integration "adams","stiff","rk","rkf","fix","discrete"
// and "root"
// Everything works but "discrete" for this problem
// investigate later...
//plotting example fancy output two y axes...
scf
(0);
clf
;
//axis y1
c = color("red")
c2 = color("black")
plot2d(t,x_vector,style=c);//black =, blue = 2, green =3, cyan = 4, red = 5
h1=
gca
();
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$t(Seconds)$","FontSize",3)
ylabel
("$X(t)$","FontSize",3);
xgrid
h1=
gca
();
h1.font_color=c;
h1.children(1).children(1).thickness =2;
xlabel
("$t(Seconds)$","FontSize",3)
ylabel
("$Displacement$","FontSize",3,"Color",5);
title
("Displacement and Velocity Versus Time","color","black");
xgrid
// Axis y2
c=color("blue");
c1 = color("red")
h2=newaxes();
h2.font_color=c;
plot2d(t,v_vector,style=c)
h2.filled="off";
h2.axes_visible(1)="off";
h2.y_location="right";
h2.children(1).children(1).thickness=2;
ylabel
("$Velocity$","FontSize",3,"color",c)
xgrid
Code from a Second Course that shows how to generate the Derivative Arrow Plot:
//Lecture 8 ME564 Matrix Systems of First Order Equations using eigenvalues
// and Eigencectors.
clc;clear "all"
disp("ME564 Lecture 8 Matrix Systems of First Order Equations",string(
datetime
()))
A=[0 1;-1.5 -.5]
y0=[1.;0.0];
t0 = 0; //Tstart
tend = 20; //Tend
t= t0:.05:tend';//time vector
//define derivativeF with an inline function
deff
("[results]=derivativeF1(t,y)","results= [A*y]")
//equivalent to MATLAB ODE45 is the following command in SciLab
//there is more options and outputs available - see the help file.
y = ode("fix",y0,t0,t,
derivativeF1
);
//disp("y=",y')
//Note: rkf has a limited number of steps like 160 maximum in this case
// use "stiff","adams","rk","fix" to move beyond 160 steps...
// according to the documentation fix is the same solver as rkf
// works without restriction
scf
(1);
clf
;
plot
(y(1,:),y(2,:),"-r","thickness",2)
xlabel
("$Position$","FontSize",3)
ylabel
("$Velocity$","FontSize",3);
title
("$ME564\ LECTURE\ 8$","color","black");
legend
('numerical',3)
xgrid
//
// the following plots the derivative arrows onto the plot
// showing the solution following the arrows.
//
xf= min(y(1,:)):(max(y(1,:))-min(y(1,:)))/10:max(y(1,:));
yf= min(y(2,:)):(max(y(2,:))-min(y(2,:)))/10:max(y(2,:));
fchamp
(
derivativeF1
,0,xf,yf)
xgrid
//
//
scf
(2);
clf
;
plot
(t,y(1,:),'-r','thickness',2)
xgrid
xlabel
("$t(Seconds)$","FontSize",3)
ylabel
("$X(t)$","FontSize",3);
title
("$ME564\ LECTURE\ 8\ Second\ Order\ Systems$","color","black");
legend
('numerical')
See what's available on ATOMS: Homepage and links repeated in the wiki/resource page.
I've personally had to use the Differential Equations, Sci-Sundials package since the regular ODE solvers in SciLab do not handle complex variables. I was doing some Fourier Transform stuff at the time.
You can also get to the additional capabilities through the menu ribbon see "Applications/Module-manager - ATOMS"
Note: Even though x range was 0.1 to 4, the program only picks up the first solution since it is simply coded to find a solution, not all solutions.
Output:
"Bisection method solution for y=2-x+ln(x) ="
0.1585943
"equation value (theoretically should be 0 for the root)="
7.230D-11
To find the other solution to the problem, one must change the x range to eliminate the first solution to x = 1 to 4.
"Bisection method solution for y=2-x+ln(x) ="
3.1461932
"equation value (theoretically should be 0 for the root)="
-2.584D-11
To understand whether you have more solutions, the only easy way is to graph the function and look for x-axis crossing points.
//Lec 5.1 Nonlinear Equation in Single Variable
//Solving Nonlinear Equations - BiSection Method.
//https://www.youtube.com/watch?v=5W46xcVInL8&t=51s&ab_channel=MATLABProgrammingforNumericalComputation
//
// Solve 2-x+ln(x)=0 using the bisection method
// Start with a segment where you think the solution exists
// Look for a sign change at the ends of the segment.
// Bisect the segment and keep the segment that contains the
// sign change. Do it until the accuracy is achieved.
//
//define the function
function [results]=
equation
(x)
results = 2.0-x+log(x);
// note log is natural log (aka ln)
//Theoretical roots are very complicated Inverse Lambert Function
//and Lambert Function solutions (approximately numerically)
// at .1585943, 3.1415926
endfunction
//Always graph your function to understand where the roots lie.
// Below is the code for a quick plot with some bells and
// whistles (title, labels, grid, and box frame) to make it
// look good.
//
x=linspace(0.1,4,1000);
results=
equation
(x);
plot2d(x',results');
title
("Y = 2 - X+ln(X)")
xlabel
("X")
ylabel
("Y")
xgrid;
gca
().box="on";
//define the segment where you think a solution lies
x = [0.1,3] //Grabs the first root
//x = [1,4] //Grabs the second root
//
while (x(2)-x(1))>1e-10;
y =
equation
(x);
// disp("y =", y);
xmid = (x(1)+x(2))/2
ymid =
equation
(xmid)
if (sign(ymid)==sign(y(1))) then
x(1)=xmid
else
x(2)=xmid
end
end
disp("Bisection method solution =" ,xmid)
z =
equation
(xmid);
disp("equation value (theoretically should be 0 for the root)=",z)
Here's the course outline - I have files for every one except for those that didn't have any coding that session. The dropped in the 17th one as an example of the files (totally random selection).
Any requests for the next file to drop in. You can also tell me to stop spamming you but my intent is to show how to do practical things in SciLab without having to spend hours upon hours looking up the syntax (which is definitely different than MATLAB in places).
//NPTEL Computer Numerical Analysis Course
//1 = "Array Operations"
//2 = "Loops and Execution Control"
//3 = "Scripts and Functions in SciLab"
//4 = "Plotting and Output in SciLab"
//5 = "Ball Travel Example -with Plotting added"
//6 = "none"
//7 = "Round-Off Errors and Iterative Methods"
//8 = "Errors and Approximations: Step-Wise & Error Propagation"