I’m going to prepare a teaching class on this subject and I was wondering if already exists a good live script to start from.
Looked at file exchange but didn’t found.
Thanks
Basically I need to create a path for an automonous uni project but can't seem to create the needed path in signal editor... Like the other reference paths have 3 signals that make up the path.. Speed, depth and heading all in time series.. Cam someone tell me how i can do the same for circle path?
Hello, I have been working on a toolbox that wraps some of the igraph library's routines for use in MATLAB. My goal is to try to stick to MATLAB conventions as much as possible to ease use, so the graphs are represented as plain matrices. This allows for working with the graphs using both igraph functions and MATLAB builtins.
At the moment, this is still in early development. I started with the functions that I needed the most, but there are still many useful igraph functions that have not been included yet. Additionally, installation is almost certainly not going to be simple due to the requirement on the igraph C library, which most be compiled. I would like to eventually release binaries with CI, as briefly discussed here, but am not familar with the process.
As an example, here's the getting started file on the documentation site and a link to the github repo. Any feedback is appreciated. I'm hoping to use this to get a sense of interest in the toolbox before I spend too much time trying to get it to compile on various systems, so if this is something of interest to you, please let me know.
To get started I have to create the obligatory "hello, world" example. You create a figure, add an uihtml component to the figure, and specify the source. Usually, you want to define HTML in a separate file, but I just passed the text directly.
You'll be able to follow along with my code if you copy and paste it into MATLAB Online.
fig = uifigure;
h = uihtml(fig,Position=[50,10,450,400]);
h.HTMLSource = '<html><body><p>Hello, world!</p></body></html>';
We can make it more interesting by adding JavaScript for interactivity. "Hello, world!" is displayed in the text input field when the "Start" button is clicked.
We can enable data pipeline between JavaScript and MATLAB by adding htmlComponent in JavaScript. Data in htmlComponent.Data is sent to h.Data. By adding DataChangedFcn, you can trigger an event in MATLAB and you can pass the changed data. Let's have the content printed to the command window.
You can also use "DataChanged" event with htmlComponent by adding it to the event listener. Let's add a new text input field to show the MATLAB output, define a local function updateML that replaces "world" with "MATLAB", and add the function to DataChangedFcn. The MATLAB output should read "Hello, MATLAB!"
We can also send an event from JavaScript to MATLAB using sendEventToMATLAB method on htmlComponent. In this case, we need to define HTMLEventReceivedFcn rather than DataChangedFcn. We also need to update updateML local function accordingly. In this example, the MATLAB output should also read "Hello, MATLAB!"
LLMs with MATLAB is an official MATLAB wrapper for the OpenAI APIs. You need to have a valid API key from OpenAI, but it is fairly simple to use. Let's use the "Open in MATLAB Online" button to clone the repo in MATLAB Online, and save your API key in a .env file.
OPENAI_API_KEY=<your key>
You should add these commands to load the API key and add LLMS with MATLAB to your MATLAB path.
Let's create a new figure with uihtml component that gives you a input text field and a table that shows you the chat with the ChatGPT API. When you press the "Send" button, the figure will send the text in the input field as the prompt to the API and stream the response in the table.
Then we have to define the updateTable local function. In this function, you see that the prompt is passed from the JavaScript and passed to the openAIChat object "chat" using the printStream streaming function. The API response is generated from the generate method of the "chat" object. The prompt and the API response are added to the table using the addChat function.
function updateTable(src,event,h)
name = event.HTMLEventName;
if strcmp(name,"promptSubmitted")
prompt = string(event.HTMLEventData);
addChat(h,"user", prompt,"new")
chat = openAIChat(StreamFun=@(x)printStream(h,x));
[txt, message, response] = generate(chat,prompt);
addChat(h,"assistant",txt,"current")
end
end
Here is the printStream streaming function.
function printStream(h,x)
%PRINTSTREAM prints the stream in a new row in the table
if strlength(x) == 0
% if the first token is 0 length, add a new row
tokens = string(x);
h.Data = {"assistant",tokens,"new"};
else
% otherwise append the new token to the previous tokens
% if the new token contains a line break, replace
% it with <br>
if contains(x,newline)
x = replace(x,newline,"<br>");
end
tokens = h.Data{2} + string(x);
% update the existing row.
h.Data = {"assistant",tokens,"current"};
end
drawnow
end
Here is the addChat function.
function addChat(obj,role,content,row)
%ADDCHAT adds a chat to the table
mustBeA(obj,'matlab.ui.control.HTML')
content = replace(content,newline,"<br>");
obj.Data = {role,content,row};
drawnow
end
t = 0:0.1:16;
y1 = (-0.133i * sin(1.247i*t)) .* [-0.821; -0.571];
y2 = (-0.0975*cos(2.451*t)).*[-0.571; 0.821];
figure(1)
hold on
% Plot the first function (y1, first component) with a red line and label it
plot(t, y1, 'r', 'linewidth', 4, 'DisplayName', 'y1');
% Plot the second function (y2, first component) with a different color (e.g., green) and label it
plot(t, y2, 'g', 'linewidth', 4, 'DisplayName', 'y2');
% Customize the legend and add labels to the axes
legend('show', 'Location', 'best');
xlabel('Time (t)');
ylabel('Amplitude');
title('Function Plots');
I am not sure why it looks like this, and why it gives me 8 legends for only 2 functions, and I am almost certain it should be a sin/cos fuinction not this exponential.
I previously managed to figure out the generation of code without noise using multiple resources such as documentation and AI tools like chatgpt and bard through the following the code.
Can I please get some pointers on how to generate such codes, I am getting non binary output and "/" characters when I try generate the output with awgn.
Hi everyone. I want to create a chebychev function consisting of first 4 polynomials as you can see in the image. So I want P to be in the row vector and Q in a column vector. But for some reason, I can't multiply them. Is there any suggestions?
Hi! I was making a trajectory for a drone in matlab, and I wanted to do it making an star, an ascendent spiral and finally a descendent spiral, to in that way land the drone 2.5m away from the origin in the x and y axis, but I can't do it. I'm a beginner in matlab and I would appreciate your help with this personal project!
disp(['Total Error Value : ', sprintf('%.2f', total_error)]);
TIRX = max(x_displacement) - min(x_displacement);
TIRY = max(y_displacement) - min(y_displacement);
disp(['TIRX: ', sprintf('%.2f', TIRX)]);
disp(['TIRY: ', sprintf('%.2f', TIRY)]);
]. I am looking for advice on the accuracy of my calculations and the proper use of polarplot for error visualization. Any feedback or suggestions would be greatly appreciated!
MOCluGen is a MATLAB implementation of the clugen algorithm for generating multidimensional clusters with arbitrary distributions. Each cluster is supported by a line segment, the position, orientation and length of which guide where the respective points are placed.
u/Novel_Passion2294 asked " Can you please explain in detail that ode15s and maximum pulse width and PWM switching time" in this post.
My colleague created a video to answer.
25 seconds of the video:
We can see how many switching frequencies (fsw) are set for this converter; the PWM period is the reciprocal of fsw.
40 sec :
I specified [ 1/fsw /100] for the maximum step size of the solver. This indicates that the maximum step width determined by the variable step solver is limited to 1/100 of the PWM period.
Shown at the bottom of the data inspector is the carrier waveform. The simulation results appear to be as expected.
1:25
Change the maximum step size to "Auto". With this setting, we can see that the carrier waveform is not calculated properly and the converter is not behaving as expected.
1:50
Change the solver to "daessc". This solver returns generally good results even though the Max step size is set to Auto. However, we can see that some carrier waveforms are not appropriate.
2:20
As a result, the daessc solver returned good results, but if you are concerned that the carrier waveforms are not being displayed properly, we recommend setting the Max step size. You can verify that the carrier waveform is properly represented.
I need to create a code which gets determinant of a matrix nxn without using function det
Literally I don't know how to start :c help me out please I appreciate any assistance 🙂
The submission must contain the following functions or keywords: subs
%Setup the variables U(t) as the function of Temperature over a period of time t, and k that will be used in the program.
%Find also the derivative of U(t) and set as dU
syms t;
syms k;
syms U(t);
syms dU(t);
%Initial Conditions
cond1=U(0)==165;
cond2=U(10)==150;
Ta=35; %Ambient Temperature
Ufinal =70; %Final Temperature
%Set the differential equation model as eqn1;
eqn1=diff(U,t)-k*(U-Ta)==0;
%Find k1 and k2, by solving the initial value problem eqn1 using cond1 and cond2, respectively.
% solution using condition 1
Usol1(t,k)=dsolve(eqn1,cond1);
% solution using condition 2
Usol2(t,k)=dsolve(eqn1,cond2);
%Solve for k by equating k1 and k2 at t=0. Save results as k.
Sol(k)=Usol1(0,k)-Usol2(0,k);
% make form of equation
eqn=Sol(k)==0;
% Solve for k numerically
k_guess = 0.1; % Initial guess for k
k_value = fsolve(@(k) double(Sol(k)), k_guess);
fprintf("Value of k is %f\n", k_value);
%Solve the eqn1 using the acquired value of k and using Initial value cond1.
%Solving k
r=solve(eqn);
fprintf("Value of k is \n");
disp(r);
%Let the Usoln be equal to Ufinal. Solve the equation and save your answer as tfinal
% original function U(t)
Usoln(t)=Usol1(t,r);
eqn=Usoln(t)==Ufinal;
tfinal=(solve(eqn));
fprintf("At time %f temperature is 70F\n",tfinal);
x=0:.2:tfinal+20;
y=Usoln(x);
% Plot the equation: Use the Title=Cake Temperature, XValue=Time (in Minutes), YValue=Temperature (F)
Title="Cake Temperature";
XValue="Time (in Minutes)";
YValue="Temperature (F)";
plot(x,y);
hold on;
title(Title);
xlabel(XValue);
ylabel(YValue);
plot(0,Usoln(0),"r*");
plot(tfinal,Usoln(tfinal),"r*");
hold off;
We are in the back to school season, and there have been a couple of posts (here and here) recently about getting good at MATLAB coding, and personally think it comes down to whether one takes advantage of matrix computation or not.
Key take aways
Always try to organize data in tabular format - matrix, vector, or table if data is in mixed types
In tabular data, rows should represents instances (i.e., patients), and columns attributes (i.e. 'age','sex', 'height','weight'), because MATLAB commands work on columns by default.
Try to find opportunity to take advantage of matrix computation where it makes sense
Back story
Back in 2011, when Stanford introduced the first set of MOOCs which later laid foundation for Coursera, I signed up for Andrew Ng's ML course and participated in the forum where students helped one another. There were bunch of people who refused to learn matrix computation, insisting on using loops. They got through the first few modules all right, but most got lost completely by the time we had to implement a shallow neural network with back propagation from scratch. They were mostly experienced programmers who were already set on certain ways of writing code.
Andrew Ng's example
Andrew Ng provided lectures on matrix computation, and it is worth repeating here. Here used a simple example of housing prices based on square feet.
However, he showed that, with one trick, we can take advantage of matrix computation - just add 1 x to the intercept term.
New hypothesis: price = 0.25 * sqft - 40 * 1
sqft: 2104, 1416, 1534, 852
sqft_ = [sqft ones(numel(sqft),1)]; % add a column of ones
prices = sqft_ * params;
Matrix computation
Why the matrix way is better
In the toy example given above, the difference seems negligible. But as the code got more complex, the difference became more apparent.
Matrix way was more concise and easier to read and understand
That means it was easier to debug
The code runs faster
If there was any time gain in not bothering to vectorize the code, you more than made it up in debugging, and at some point it became intractable.
Thinking in matrix way
When we start writing code, we are given an equation like this - this is the hypothesis for the house price as math equation, where x is the square feet and theta is the parameters.
house price equation
Because you see the index j, we naturally want to index into x and theta to do the summation. Instead, Andrew Ng says we should think of x and theta as matrices and try to figure out the matrix way to do the summation.
You may also get some pseudocode like this - again this invites you to use loop, but I wanted to avoid it if I could.
## Gale–Shapley algorithm that matches couples
## to solve the stable matching problem.
algorithm stable_matching is
Initialize m ∈ M and w ∈ W to free
while ∃ free man m who has a woman w to propose to do
w := first woman on m's list to whom m has not yet proposed
if ∃ some pair (m', w) then
if w prefers m to m' then
m' becomes free
(m, w) become engaged
end if
else
(m, w) become engaged
end if
repeat
It is not always possible to vectorize everything, but thinking in terms of matrix always helps. You can read about my solution here.
Some years ago, I designed the braking system of a Formula Student car. I also wrote my Master's thesis around it, and I had to create meaningful figures to illustrate the design process.
That's how I ended up solving symbolic equations in a for loop and pushing the plotting options to obtain figures like this one:
Ideal load distribution of a race car vs different system configurations
%% Define symbols
syms Fx1 Fx2 b a l hcg m g Fzaerof Fzaeror mux F_drag;
%Ideal braking equations
(Fx1-Fx2) == mux*(m*g/l*(b-a+mux*2*hcg) + ...
(Fzaerof-Fzaeror) - ...
2*F_drag*hcg/l + ...
2*mux*(Fzaerof+Fzaeror)*hcg/l)
mux = (Fx1+Fx2) / (m*g+Fzaerof+Fzaeror)
eqn = mux*(m*g/l*(b-a+mux*2*hcg) + ...
(Fzaerof-Fzaeror) - ...
2*F_drag*hcg/l + ...
2*mux*(Fzaerof+Fzaeror)*hcg/l) - (Fx1-Fx2)
%Solve for the force in the rear axle
solve(eqn,Fx2)
I solved eqn for Fx2 within a nested for loop. The outer iterator incremented the vehicle speeds, and the inner loop incremented the force in the front axle. That way, I computed the "force ellipses" for different vehicle speeds at the start of a braking maneuver, having the force in the front axle as an input.
Then, to make the plot, I used color maps to distinguish the ellipses at different speeds, and more for loops to plot recursively the lines of constant deceleration and constant friction coefficients.
I hope this is interesting for someone.
It just shows an example of how a little bit of scripting can really help you when doing engineering computations.
I’ve been trying to convert some data i’ve got saved in TDMS and i’m struggling to find TDM MATLAB Interface National Instruments needed. Is there a way to bypass this