GNU Octave math programming - Page 1
Forum section: electronics / general

author: MathWizard
author_rank: Super Contributor
timestamp: December 09, 2020, 11:04:15 pm
content: I've spent a few hours fooling around with GNU octave, which is like Matlab. And I've barely done programing, so I'm finding it difficult to understand the syntax, layout, structure of stuff, but is common to people that do programming all the time. It's based on C and C++.I find the help files need a help file to explain the common programming notations, and so have I haven't found much worked examples, to copy and try. I've watched a few video's, made a script to solve for the time constants and stuff in RLC circuits. I'm trying to make the ODE solver work with 2 coupled equations, to make lsode thing work.Anyone know a good guide for Octave, and programming, for people that barely do it ? I'm trying not to get too off track from EE.Or what crash course on programming, would be the most like Octave, and preferably, be about physics/math, since at least I have that to anchor some programming around.Here's my simple RLC calulator so far, but i haven't figured out how to get lsode notation and stuff working right for the coupled linear ode's#partsR=200L=0.5C=100e-6series = 0#time constantsif ((series = 0))A = 1/(2*R*C)elseA= R/(2*L)endifWo = 1/sqrt(L*C)cp = [ 1, 2*A, Wo^2]roots (cp)end>> roots (cp)ans =-341.421-58.579

author: ivaylo
author_rank: Frequent Contributor
timestamp: December 10, 2020, 05:41:29 am
content: Are you trying to get into programming or to solve math/physics problems with a computer? Or solve something very specific for which you need Octave/Matlab? Generally using those as your first programming language would be awkward, but providing a bit more context what are you trying to do will get you better answers...

author: Kibabalu
author_rank: Regular Contributor
timestamp: December 10, 2020, 07:32:47 am
content: Regarding syntax and restrictions you can use any teaching material for Matlab. But my strong recommondation is to learn Python instead. Octave has the same focus and restrictions like Matlab, but without its many available really advanced toolboxes. I would not recommend Matlab either (Gave Matlab courses for more than 15 years).Go for Python! Or if you insist of learning something exotic, go for Julia: As fast as python should be ;-)

author: DiTBho
author_rank: Super Contributor
timestamp: December 10, 2020, 08:55:18 am
content: Python + Numpy ?

author: PKTKS
author_rank: Super Contributor
timestamp: December 10, 2020, 11:46:42 am
content: Quote from: MathWizard on December 09, 2020, 11:04:15 pmWell one the very first things they made me learn way backin academia was FORTRAN (and COBOL) just before and extensiveASSEMBLY course...Today I can see that no matter what crappy shit someonepatent.. you still need the raw power or programsand scientific languages are indispensable.Try the crash course here on this ref.http://www2.informatik.uni-freiburg.de/~arras/resources.htmlhttp://srl.informatik.uni-freiburg.de/downloadsdir/Octave-Matlab-Tutorial.pdfand I hardly doubt anyone will benefit such powerful app like octavewithout full programming skillsPaul

author: ledtester
author_rank: Super Contributor
timestamp: December 10, 2020, 12:56:58 pm
content: I would also suggest python and have a look at sympy.The docs for the sympy ODE solver:https://docs.sympy.org/latest/modules/solvers/ode.htmlYou can also run sympy from a browser athttps://live.sympy.org/

author: PKTKS
author_rank: Super Contributor
timestamp: December 10, 2020, 02:03:41 pm
content: try as wellhttps://metacpan.org/pod/Math::ODEAs far as I can tell it is more focused andshould be faster as all PERL modules aredirectly C binded and the APIs are very skinnyPaul

author: magic
author_rank: Super Contributor
timestamp: December 10, 2020, 09:52:28 pm
content: Quote from: MathWizard on December 09, 2020, 11:04:15 pmPlease use code tags for that kind of stuff.I'm not sure if this snippet is supposed to be right or wrong or what help you need with it, but a few remarks are in order:- comparison is == rather than = - not sure about Matlab/Octave but it backfires really badly in C- terminate lines with ; if you don't want the result to be printed - you will appreciate it with larger matricesSorry, I don't have links to introductory materials, it's been a long while.For any concrete Matlab function/library it should be possible to find examples in documentation or at places like StackOverflow.Quote from: PKTKS on December 10, 2020, 02:03:41 pmAhem,

author: PKTKS
author_rank: Super Contributor
timestamp: December 11, 2020, 10:58:12 am
content: Quote from: magic on December 10, 2020, 09:52:28 pmMultiply the crazy scared little guy with the whole team:https://metacpan.org/pod/Math::BLAShttps://metacpan.org/pod/Math::Lapackhttps://metacpan.org/pod/PDLhttps://metacpan.org/pod/Math::Parihttps://metacpan.org/pod/Math::FFThttps://metacpan.org/pod/PDL::FFThttps://metacpan.org/pod/Math::Symbolic::MaximaSimplehttps://metacpan.org/pod/Inline::Octavehttps://metacpan.org/pod/Math::ODEIn short a whole interface for whatever you may need indata analysis ... including BLAS LAPACK FFT with properinterfaces to octave and maxima..Paul

author: rstofer
author_rank: Super Contributor
timestamp: December 11, 2020, 05:01:47 pm
content: Here is the Lorenz Attractor for MATLAB. It runs in Octave but the plot step size is too large and the plots are not very neat. It works great in MATLAB. Fixing it for Octave is left as an exercise for the reader.Code:%Lorenz Equationsig=10; b=8/3; r=24.5;f=@(t,y)[sig*(y(2)-y(1)); r*y(1)-y(2)-y(1)*y(3);y(1)*y(2)-b*y(3) ];[t,y]=ode45(f,[0 50],[-50; 0; 50]);%Plot of x and y versus tfigure(1)plot(t,y(:,1),t,y(:,2))title('9.3.7 Plot X and Y versus t')xlabel('t')ylabel('x and y')legend('x','y')%Plot of x and zfigure(2)plot(y(:,1), y(:,3))title('9.3.7 Plot of X versus Z')xlabel('x')ylabel('z')figure(3)plot3(y(:,1),y(:,2),y(:,3))title('9.3.7 3D Plot')xlabel('x')ylabel('y')zlabel('Z')It is a system of 3 cross coupled ODEs:https://en.wikipedia.org/wiki/Lorenz_systemThere is also an RLC circuit. Unzip the two files and run the RLCexample.m file. It will find the RLC.m function file.For the Python crowd (I am using Spyder 4):I have been working through a book "Deep Learning From Scratch ... " which gets deeply into partial differential equations. Here is the code for an example early in the book:Code:# -*- coding: utf-8 -*-import matplotlib.pyplot as pltimport numpy as npfrom numpy import ndarray%matplotlib inlinefrom typing import Callablefrom typing import ListArray_Function = Callable[,ndarray]Chain = Listdef square(x: ndarray) -> ndarray:return np.power(x, 2)def sigmoid(x:ndarray) -> ndarray:return 1/(1+np.exp(-x))def chain_length_2(chain: Chain,x: ndarray) -> ndarray:'''Evaluates two functions in a row, in a "Chain".'''assert len(chain) == 2, \"Length of input 'chain' should be 2"f1 = chainf2 = chainreturn f2(f1(x))def deriv(func: Callable[,ndarray],input_:ndarray,delta: float = 0.001) -> ndarray:return (func(input_ + delta) - func(input_ -delta))/(2*delta)def chain_deriv_2(chain:Chain,input_range:ndarray)->ndarray:assert len(chain) == 2,\"This function requires 'Chain' objects of length 2"assert input_range.ndim == 1,\"Function requires a 1 dimensional ndarray as input"f1 = chainf2 = chainf1_of_x = f1(input_range)df1dx = deriv(f1,input_range)df2du = deriv(f2,f1_of_x)return df1dx * df2dudef chain_deriv_3(chain:Chain,input_range:ndarray)->ndarray:assert len(chain) == 3, \"This function requires 'Chain' objects of length 3"f1 = chainf2 = chainf3 = chainf1_of_x = f1(input_range)f2_of_x = f2(f1_of_x)df3du = deriv(f3,f2_of_x)df2du = deriv(f2,f1_of_x)df1dx = deriv(f1,input_range)return df1dx*df2du*df3dudef plot_chain(ax,chain: Chain,input_range: ndarray) -> None:'''Plots a chain function - a function made up ofmultiple consecutive ndarray -> ndarray mappings -Across the input_rangeax: matplotlib Subplot for plotting'''assert input_range.ndim == 1, \"Function requires a 1 dimensional ndarray as input_range"output_range = chain_length_2(chain, input_range)ax.plot(input_range, output_range)def plot_chain_deriv(ax,chain: Chain,input_range: ndarray) -> ndarray:'''Uses the chain rule to plot the derivative of a function consisting oftwo nested functions.ax: matplotlib Subplot for plotting'''output_range = chain_deriv_2(chain, input_range)ax.plot(input_range, output_range)fig, ax = plt.subplots(1, 2, sharey=False, figsize=(16, 8)) # 2 Rows, 1 Colchain_1 = [square, sigmoid]chain_2 = [sigmoid, square]PLOT_RANGE = np.arange(-3, 3, 0.01)plot_chain(ax, chain_1, PLOT_RANGE)plot_chain_deriv(ax, chain_1, PLOT_RANGE)ax.legend(["$f(x)$", "$\\frac{df}{dx}$"])ax.set_title("Function and derivative for\n$f(x) = sigmoid(square(x))$")ax.grid()plot_chain(ax, chain_2, PLOT_RANGE)plot_chain_deriv(ax, chain_2, PLOT_RANGE)ax.legend(["$f(x)$", "$\\frac{df}{dx}$"])ax.set_title("Function and derivative for\n$f(x) = square(sigmoid(x))$");ax.grid()It produces a couple of plots of chained functions and their derivative. Notice how the derivative is calculated. Just like the slope process from Calc I.https://www.amazon.com/gp/product/1492041416I omitted my preferred method of dealing with differential equations: MATLAB and SimuLink. Just plunk down integrators and gain blocks, wire them up and hit the "Go" button. This is the analog computer approach. Lord Kelvin rules!

author: rstofer
author_rank: Super Contributor
timestamp: December 11, 2020, 05:34:49 pm
content: Here's a MATLAB solution to a simple algebra problem (if solving 6 simultaneous equations is your cup of tea)Code:% A football stadium has a capacity of 100,000 attendees% Ticket prices:% Student = $25% Alumni = $40% Faculty = $60% Public = $70% Veterans = $32% Guests = $ 0% A full capacity game netted $4,987,000% Let S = number of students, A = number of alumni, F = number of faculty% P = number of public, V = number of veterans, G = number of guests% S A F P V G = valueM = [ 1 1 1 1 1 1 100000; ... % total number of attendees25 40 60 70 32 0 4897000; ... % total revenue0 1 -1 0 0 0 11000; ... % 11000 more alumni than faculty0 1 0 1 -10 0 0; ... % public + alumni = 10 * veterans-1 1 1 0 0 0 0; ... % alumni + faculty = students1 0 1 0 -4 -4 0]; % faculty + students = 4 (guests + veterans)A = M(:,1:6); % extract 6x6 matrixB = M(:,7); % extract value column vectorP = M(2,1:6); % ticket price by attendee typeR = inv(A)*B; % compute number of attendees by typeT = sum(R); % check total attendees = 100,000 CHECKU = P*R; % total revenue = 4,897,000 CHECKV = R'.*P; % revenue by attendee type - transpose R from 6x1 to 1x6% then do element by element multiplication%% fancy output, all previous default output semicoloned%label = {'Students' 'Alumni' 'Faculty' 'Public' 'Veterans' 'Guests'};for i = 1:6fprintf('%-8s%7d @ %2d = %7d\n',string(label(i)),...round(R(i)),...M(2,i),...round(V(i)))endfprintf('\nTotals %6d %8d\n',round(T), round(U))Results:Code:Students 25000 @ 25 = 625000Alumni 18000 @ 40 = 720000Faculty 7000 @ 60 = 420000Public 42000 @ 70 = 2940000Veterans 6000 @ 32 = 192000Guests 2000 @ 0 = 0Totals 100000 4897000A statement likeCode:A = M(:,1:6); % extract 6x6 matrixmeans fill a matrix A with all the rows of matrix M but only columns 1 through 6. I created M with 7 columns so I could document the output of each row. Then I break it into a 6x6 and 6x1 matrix to solve the equations.It is much easier to start with something like this than to jump into differential equations. The syntax of MATLAB/Octave isn't all that simple. About the only way to learn it is to write it and slog through the errors.There are hundreds of MATLAB books and I have a dozen or so. Pick one, any one, and work through some problems. Many books are of the "MATLAB For Physics" or other specific application.Same story with Python - only far worse. How Python is taught is highly dependent on a supposed application. The Python syntax idea of using starting column to denote code level is wretched. Spaces shouldn't be a syntactic element. Nevertheless, Python is important, not because of the language, but because of the libraries.Again, there are hundreds of books on Python and they too will tend to be application oriented. "PYTHON for Physics", that kind of thing. That "...Deep Learning..." book I linked above is an example.

author: RoGeorge
author_rank: Super Contributor
timestamp: December 11, 2020, 05:43:45 pm
content: If you know Matlab you know Octave, too, they are the same.Either one, they were not meant to be a yet another programming language, but rather a math tool for numeric simulation and plotting the results. Using them as a programming language is possible, but not the best thing to use them for.Programing is usually made with loops, while in Matlab/Octave/IPython/etc. an array should be preferred/used to calculate all values at once, rather than a loop.<--- this is what bamboozles at first, when coming from programmingOperators are usually for arrays, too, e.g. '*' (star) is a multiplier for arrays, while the symbol '.*' (dot star) is for multiplying element by element. same for + and .+ and so on. Dot in front of operator is for doing the operation element by element, or else is a matrix operator.That's it.Also, plots and charts are almost identical with the ones from matplotlib.pyplot, as a programmer you may want to jump straight to Python, the math libs are usually the same no matter what language use. Python is just a wrapper, yet way more productive than using those number crunching libraries from their native language. Some prefers to use other languages, depends on personal habits, but for now Python is probably the richest and most productive language to use.Alternatives to Octave/Matlab, for plotting and learning:- LTspice for electronic simulations (mentioned because of the RC circuit example you gave for Octave)- Python with corresponding modules, or Anaconda if you just want the whole setup to work and don't mind extra bloat- Jupyter Notebook, sometimes used in various EE/Physics/Programming/etc. tutorials you may want to run for yourself- GeoGebra (interactive, easy to set sliders, webpage based or local install)My recommendation is to go withPython. I wouldn't invest much time learning Matlab/Octave, but rather Python and its math/science modules like numpy, matplotlib, sympy, etc.In the last decade or so, the scientific community is steadily migrating to Python.

author: rstofer
author_rank: Super Contributor
timestamp: December 11, 2020, 06:14:04 pm
content: Quote from: RoGeorge on December 11, 2020, 05:43:45 pmHm... What about SimuLink? There are many applications where simulations are easier to work with than hardwired equations. I agree that Python is the thing to learn right up until simulations of mechanical systems become important.

author: MathWizard
author_rank: Super Contributor
timestamp: December 11, 2020, 06:47:45 pm
content: Ok thanks for some links there guys, I want to be able to plot stuff I'm looking at, and program stuff to save time on the calculator....although I like using that too, but yeah it sure is quicker to run some beginner code.In the past I would have used spreadsheets to automate some calulations.As for coding stuff w/ Python vs a deicated math program, how hard is it to plot functions/etc w/ Python ? I suppose people have already made stuff for that.I certainly don't want to be trying to generate grapics on screen, line by line, choozing border size, or any of that stuff I remember from creating a webpage years ago in school.I'm sure there's stand alone ODE solver's too, but I want to do some programming too anyways.

author: RoGeorge
author_rank: Super Contributor
timestamp: December 11, 2020, 07:10:46 pm
content: Quote from: rstofer on December 11, 2020, 06:14:04 pmIDK, am not a guru, system simulations can be done from Python (and modules) but not as easy as from Simulink. To me, so far Python was the winner, but that doesn't mean other specialized tools are of no good.I think Scilab is for Octave what Simulink is for Matlab, but Scilab and Simulink are not as compatible to each other as Octave with Matlab is. Only used Scilab/Simulink a couple of times (in some lessons about PID loops and systems stability analysis), so I don't really know them enough to comment.The most appealing feature to me (thought it was not used in those lessons I mentioned) was the ability to interact with real hardware and real data streams, like for example lab instruments, single board computers, Arduinos, soundcards, serial ports, etc.When it's to interact with hardware (in production, not for learning purposes), LabVIEW is the tool I prefer as a graphical programming language (now free for home use), or maybe something much smaller and open source, like GNU Radio (it lets one add/define its own function blocks and hardware devices, so it's not for software define radios only, but mostly for live stream data processing oriented, IMO).In the end it all depends of the final goal, personal preferences, skills, and also the available budget of time vs money.

author: CatalinaWOW
author_rank: Super Contributor
timestamp: December 11, 2020, 07:11:47 pm
content: I don't have any solutions for the OP, but will sympathize with his frustration. Each program and language has an intrinsic world view which may or may not click with a particular user immediately. With enough need and time this can be overcome, but those are usually painful during the transition.The differences can be subtle. You would think all spreadsheets are the same, but after working in SuperCalc, Lotus 123 and Quattro I found the transition to Excel difficult. And I share with many the difficulty of transitioning from pre-2003 MS Office to later versions.And I also am one who has found Matlab/Octave difficult. In my case manipulation of data once it is in is fairly routine, but I do have a persistent block on easy, efficient and repeatable ways to get data in and out. Mental block on my part, but it is real.

author: rstofer
author_rank: Super Contributor
timestamp: December 11, 2020, 07:16:56 pm
content: Quote from: MathWizard on December 11, 2020, 06:47:45 pmReply #9 has Python code (save as Fundamentals.ipy - the .i in .ipy is REQURED). This is a rather complex set of plots, not in the plotting, that is easy, but in the creation of the derivatives of chained functions.Install Spyder 4 to use the code and after you press the dark green run button, the plots show up in the Plots tab over on the right of the screen.Here is something from GoogleAgain, save this code as SineWave.ipy and run it inside Spyder 4Code:import matplotlib.pyplot as pltimport numpy as np%matplotlib inlineFs = 8000f = 5sample = 8000x = np.arange(sample)y = np.sin(2 * np.pi * f * x / Fs)plt.plot(x, y)plt.xlabel('sample(n)')plt.ylabel('voltage(V)')plt.show()It doesn't get much easier than this! It probably works in every other IDE but I'm using just Spyder 4.I went back and added the plot output from Fundamentals.ipy to Reply #9. It looks pretty nice considering how little effort goes into it.

author: RoGeorge
author_rank: Super Contributor
timestamp: December 11, 2020, 07:22:36 pm
content: Quote from: MathWizard on December 11, 2020, 06:47:45 pmIt's trivial to plot from Python, same if not easier than it is to do it from Matlab/Octave.This is matplotlib can:https://matplotlib.org/gallery/index.htmlSome intro from docs:https://matplotlib.org/tutorials/introductory/pyplot.htmlAs a decent but easy to use IDE for Python (that also remembers the plots) I am using Spyder:https://www.spyder-ide.org/

author: rstofer
author_rank: Super Contributor
timestamp: December 11, 2020, 09:08:53 pm
content: Then there is the way we did plotting back around '70. About 270 lines of Fortran (including a bunch of comments) to create a plot that has a lot of stuff on the page.No matter how ugly plotting may seem today, it doesn't compare to how detailed we had to be back in the early years.This example is from one of my grandson's math books - Pre-Calc, I think.FWIW, this code is for the IBM1130 using Fortran and a CalComp 1627 drum plotter. A lifesaver when coupled to the output of the IBM Electronic Circuit Analysis Program (ECAP) to create Bode' plots. Perfect for the young fellow going to EE school.I have an FPGA implementation of the IBM1130 so the code is native and it's real. The FPGA runs all of the IBM software, unchanged.http://ibm1130.org/hw/io/

author: PKTKS
author_rank: Super Contributor
timestamp: December 12, 2020, 01:27:21 pm
content: Well ... things changed (evolved) quite a lot since thosegone days of 70s FORTRAN...My system BLAS and LAPACK libraries are indeedcompiled with FORTRAN bindings but also with Cbindings as well.And PERL wraps those binding absolute fastest thananything available. Comparing mature code like BLASLAPACK, PARI and FFT with some recent newbie stuffis just impossible.We shall see how hard is a modern mature implementationof such decades of tested code ...For example a simple singularity disturbance fieldhow hard should we have to INTERACT WITH N-DIMENSIONAL3d terminal plots .. (GLUT is builtin in PDL) or gnuplotexternally binded terminal..Hands on... on the figure..PDL is an interactive PERL SHELL with functionalityabove what octave can provide..There is not much similitude with those FORTRAN 77 days..nevertheless BLAS and LAPACK are still compiled in FORTRANon my system.Paul

author: PKTKS
author_rank: Super Contributor
timestamp: December 12, 2020, 01:38:21 pm
content: ... forgot to mention the handy MAN page placedthere... just to help me remember...After a proper reasonable level of skills thereshould be no return to anything inferior to this level..Access to those mature code (BLAS LAPACK FFT PARI)is orders of magnitude more easier than before..The figure speaks per si...Paul

author: Dhela
author_rank: Newbie
timestamp: March 09, 2025, 03:04:19 pm
content: # Circuit ComponentsR = 200;L = 0.5;C = 100e-6;series = 0; # 0 for parallel, 1 for series# Time parameterst = linspace(0, 0.1, 1000); # Time vector from 0 to 0.1s# Initial conditions (Vc = 10V, IL = 0A)X0 = [10; 0];# Define the ODE systemfunction dX = rlc_ode(X, t, R, L, C, series)Vc = X(1);Il = X(2);if (series == 1)# Series RLC equationsdIl = (-Vc - R*Il)/L;dVc = Il/C;else# Parallel RLC equationsdVc = (-Il - Vc/R)/C;dIl = Vc/L;endifdX = [dVc; dIl];endfunction# Solve using lsode with parameter passingX = lsode(@(X, t) rlc_ode(X, t, R, L, C, series), X0, t);# Plot resultsfigure(1);clf;plot(t, X(:, 1), "r;Capacitor Voltage (V);", t, X(:, 2), "b;Inductor Current (A);");xlabel("Time (s)");title("RLC Transient Response");grid on;

author: radiolistener
author_rank: Super Contributor
timestamp: March 10, 2025, 04:43:57 am
content: Quote from: Dhela on March 09, 2025, 03:04:19 pmsome comments on your code in order to keep the code compatible for both - Octave and MATLAB:1) do not use # for comments, because it is not supported on MATLAB, use % instead2) do not use `endif`/`endfunction`, because they are not supported on MATLAB, use `end` insteadHere is fixed code which works on Octave and MATLAB:Code:% Circuit ComponentsR = 200;L = 0.5;C = 100e-6;series = 0; % 0 for parallel, 1 for seriestspan = [0 0.1]; % Time range from 0 to 0.1sX0 = [10; 0]; % Initial conditions (Vc = 10V, IL = 0A)t = linspace(tspan(1), tspan(2), 1000); % Time vector% Define the ODE systemfunction dX = rlc_ode(X, t, R, L, C, series)Vc = X(1);Il = X(2);if (series == 1)% Series RLC equationsdIl = (-Vc - R*Il)/L;dVc = Il/C;else% Parallel RLC equationsdVc = (-Il - Vc/R)/C;dIl = Vc/L;enddX = [dVc; dIl];endisOctave = exist('OCTAVE_VERSION', 'builtin') ~= 0;if isOctave% Solve using lsode with parameter passingX = lsode(@(X, t) rlc_ode(X, t, R, L, C, series), X0, t);else% Solve using ode45[t, X] = ode45(@(t, X) rlc_ode(X, t, R, L, C, series), tspan, X0);end% Plot resultsfigure(1);clf;plot(t, X(:, 1), 'r', 'DisplayName', 'Capacitor Voltage (V)');hold on;plot(t, X(:, 2), 'b', 'DisplayName', 'Inductor Current (A)');xlabel('Time (s)');ylabel('Response');title('RLC Transient Response');legend show;grid on;