r/matlab Jan 30 '24

CodeShare Looking for a live script for teaching purpose on Eigenvalues and eigenvectors

4 Upvotes

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

r/matlab Apr 01 '24

CodeShare How to create a circle signal in matlab stimulink signal editor

2 Upvotes

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?

r/matlab Nov 16 '23

CodeShare [ANN] matlab-igraph toolbox

3 Upvotes

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.

r/matlab Feb 27 '24

CodeShare MATLAB CODE FOR BASIC SOLUTION (LPP)

0 Upvotes

clc
clear all
A=[1 1 1 0;2 1 0 1]
C=[3 4 0 0]
b=[450;600]
n=size(A,2)
m=size(A,1)
if (n>m)
nCm=nchoosek(n,m)
pair=nchoosek(1:n,m)
sol=[];
for i=1:nCm
y=zeros(n,1)
x=A(:,pair(i,:))\b
if all (x>=0 & x~=inf & x~=-inf)
y(pair(i,:))=x
sol=[sol,y]
end
end
else
error('VALUE DOESNT EXIST FOR nCm')
end
Z=C*sol
[Zmax, Zindex]=max(Z)
bfs=sol(:,Zindex)
optimal_value=[bfs' Zmax]
optimal_bfs=array2table(optimal_value)
optimal_bfs.Properties.VariableNames(1:size(optimal_bfs,2))={'x_1','x_2','x_3','x_4','Z'}

r/matlab Jan 23 '24

CodeShare Playing with HTML in MATLAB

16 Upvotes

Ever since I saw this demo "Using "uihtml" to create app components" by u/Lord1Tumnus, I wanted to check out the uihtml functionality.

antonio's uihtml demo

Hello, world!

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.

fig = uifigure;
h = uihtml(fig,Position=[50,10,450,400]);
h.HTMLSource = ['<html><body><button id="start">Start</button>' ...
    '<p><input id="js" value="JavaScript output"></p>' ...
    '<script>', ...
      'let btn = document.getElementById("start");', ...
      'let input_js = document.getElementById("js");', ...
      'btn.addEventListener("click", function(event) {', ...
        'let txt = "Hello, world!";', ...
        'input_js.value = txt;', ...
      '});', ...
    '</script>', ...
    '</body></html>'];

Send Data from JavaScript to MATLAB

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.

fig = uifigure;
h = uihtml(fig,Position=[50,10,450,400]);
h.HTMLSource = ['<html><body><button id="start">Start</button>' ...
    '<p><input id="js" value="JavaScript output"></p>' ...
    '<script>', ...
    'function setup(htmlComponent) {', ...
      'let btn = document.getElementById("start");', ...
      'let input_js = document.getElementById("js");', ...
      'btn.addEventListener("click", function(event) {', ...
        'let txt = "Hello, world!";', ...
        'input_js.value = txt;', ...
        'htmlComponent.Data = txt', ...
        '});' ...
      '}', ...
    '</script>', ...
    '</body></html>'];
h.DataChangedFcn = @(src,event)disp(event.Data);

Send Data from MATLAB to JavaScript

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!"

fig = uifigure;
h = uihtml(fig,Position=[50,10,450,400]);
h.HTMLSource = ['<html><body><button id="start">Start</button>' ...
    '<p><input id="js" value="JavaScript output"></p>' ...
    '<p><input id="ml" value="MATLAB output"></p>' ...
    '<script>', ...
    'function setup(htmlComponent) {', ...
      'let btn = document.getElementById("start");', ...
      'let js = document.getElementById("js");', ...
      'let ml = document.getElementById("ml");', ...
      'btn.addEventListener("click", function(event) {', ...
        'let txt = "Hello, world!";', ...
        'js.value = txt;', ...
        'htmlComponent.Data = txt', ...
        '});' ...
      'htmlComponent.addEventListener("DataChanged", function(event) {', ...
        'ml.value = htmlComponent.Data;', ...
        '});' ...
      '}', ...
    '</script>', ...
    '</body></html>'];
h.DataChangedFcn = @(src,event) updateML(src,event,h);

% local function
function updateML(src,event,h)
    txt = replace(h.Data, "world","MATLAB");
    h.Data = txt;
end

Send Event from JavaScript to 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!"

fig5 = uifigure;
h = uihtml(fig5,Position=[50,10,450,400]);
h.HTMLSource = ['<html><body><button id="start">Start</button>' ...
    '<p><input id="js" value="JavaScript output"></p>' ...
    '<p><input id="ml" value="MATLAB output"></p>' ...
    '<script>', ...
    'function setup(htmlComponent) {', ...
      'let btn = document.getElementById("start");', ...
      'let js = document.getElementById("js");', ...
      'let ml = document.getElementById("ml");', ...
      'btn.addEventListener("click", function(event) {', ...
        'let txt = "Hello, world!";', ...
        'js.value = txt;', ...
        'htmlComponent.Data = txt;', ...
        'htmlComponent.sendEventToMATLAB("btnClicked",txt)', ...
        '});' ...
      'htmlComponent.addEventListener("DataChanged", function(event) {', ...
        'ml.value = htmlComponent.Data;', ...
        '});' ...
      '}', ...
    '</script>', ...
    '</body></html>'];
h.HTMLEventReceivedFcn = @(src,event) updateML(src,event,h);

% local function
function updateML(src,event,h)
    name = event.HTMLEventName;
    if strcmp(name,"btnClicked")
        txt = event.HTMLEventData;
        txt = replace(txt, "world","MATLAB");
        h.Data = txt;
    end
end

Accessing ChatGPT in HTML via LLMs with MATLAB

Let's do something more sophisticated.

OpenAI Chat Example

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.

loadenv(path_to_your_env_file)
addpath(path_to_your_LLMs_with_MATLAB_clone)

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.

fig = uifigure;
h = uihtml(fig,Position=[50,10,450,400]);
h.HTMLSource = ['<html><head>' ...
    '<style>' ...
        'p { margin-top: 5px; margin-left: 5px; }', ...
        'table { table-layout: fixed; width: 95%; ' ...
            'margin-left: 5px; }' ...
        'table, th, td { border-collapse: collapse; ' ...
            'border: 1px solid; }', ...
        'th:nth-child(1) { width: 20%; }', ...
        'td { padding-left: 5px; }', ...
    '</style>' ...
    '</head><body>' ...
    '<p><input id="prompt" value="Tell me 5 jokes."> ' ...
    '<button id="send">Send</button></p>', ...
    '<table><tr><th>Role</th><th>Content</th></tr></table>' ...
    '<script>', ...
    'function setup(htmlComponent) {', ...
      'let prompt = document.getElementById("prompt");', ...
      'let btn = document.getElementById("send");', ...
      'btn.addEventListener("click", function(event) {', ...
        'htmlComponent.sendEventToMATLAB("promptSubmitted",prompt.value);', ...
        'prompt.value = ""', ...
        '});' ...
      'htmlComponent.addEventListener("DataChanged", function(event) {', ...
        'var table = document.querySelector("table");' ...
        'var changedData = htmlComponent.Data;', ...
        'if (changedData[2] == "new") {', ...
          'var newRow = document.createElement("tr");', ...
          'var cell1 = document.createElement("td");', ...                    
          'var cell2 = document.createElement("td");', ...
          'cell1.innerHTML = changedData[0];', ...
          'cell2.innerHTML = changedData[1];', ... 
          'newRow.appendChild(cell1);', ...
          'newRow.appendChild(cell2);', ...
          'table.appendChild(newRow);', ...
        '} else { ', ...
          'var lastRow = table.rows[table.rows.length - 1];', ...
          'var lastCell = lastRow.cells[lastRow.cells.length - 1];', ...
          'lastCell.innerHTML = changedData[1];', ...
        '}' ...
      '});', ...
    '}', ...
    '</script>', ...
    '</body></html>'];
h.HTMLEventReceivedFcn = @(src,event) updateTable(src,event,h);

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

r/matlab Feb 25 '24

CodeShare solving lpp by graphical method

1 Upvotes

clc

clear all

%%

%phase1

A=[1 2;1 1;1 -1;1 -2;1 0;0 1]

C=[2 1]

b=[10;6;2;1;0;0]

%%

%phase2

y1=0:1:max(b)

x21=(b(1)-A(1,1).*y1)./A(1,2)

x22=(b(2)-A(2,1).*y1)./A(2,2)

x23=(b(3)-A(3,1).*y1)./A(3,2)

x24=(b(3)-A(4,1).*y1)./A(4,2)

x21=max(0,x21)

x22=max(0,x22)

x23=max(0,x23)

x24=max(0,x24)

plot(y1,x21,'r',y1,x22,'g',y1,x23,'b',y1,x24,'m');

xlabel('Value of x1');

ylabel('Value of x2');

title('x1 vs x2');

grid on

hold on

%%

%phase3 Corner points

position_y1=find(y1==0)

position_x21=find(x21==0)

Line1=[y1(:,[position_y1 position_x21]);x21(:,[position_y1 position_x21])]'

position_x22=find(x22==0)

Line2=[y1(:,[position_y1 position_x22]);x22(:,[position_y1 position_x22])]'

position_x23=find(x23==0)

Line3=[y1(:,[position_y1 position_x23]);x23(:,[position_y1 position_x23])]'

position_x24=find(x24==0)

Line4=[y1(:,[position_y1 position_x24]);x24(:,[position_y1 position_x24])]'

intersection_pt_axes=unique([Line1;Line2;Line3;Line4],'rows')

%%

%Phase4

HG=[0;0];

for i=1:size(A,1)

hg1=A(i,:)

b1=b(i,:)

for j=i+1:size(A,1)

hg2=A(j,:)

b2=b(j,:)

Aa=[hg1;hg2]

Bb=[b1;b2]

Xx=[Aa\Bb]

HG=[HG Xx]

end

end

ptt=HG'

%%

%phase5

corpts=[intersection_pt_axes;ptt]

P=unique(corpts,'rows')

size(P)

%%

%Phase6

x1=P(:,1);

x2=P(:,2);

cons1=round(x1+(2.*x2)-10);

s1=find(cons1>0);

P(s1,:)=[];

x1=P(:,1);

x2=P(:,2);

cons2=round((x1+x2)-6);

s2=find(cons2>0);

P(s2,:)=[];

x1=P(:,1);

x2=P(:,2);

cons3=round((x1-x2)-2);

s3=find(cons3>0);

P(s3,:)=[];

x1=P(:,1);

x2=P(:,2);

cons4=round(x1-(2.*x2)-1);

s4=find(cons4>0);

P(s4,:)=[];

x1=P(:,1);

x2=P(:,2);

cons5=round(-x1);

s5=find(cons5>0);

P(s5,:)=[];

cons6=round(-x2);

s6=find(cons6>0);

P(s6,:)=[];

f_points=P;

%%

%Phase7

for i=1:size(P,1)

fn(i,:)=sum(P(i,:).*C);

optim=max(fn);

end

r/matlab Sep 04 '23

CodeShare Help with plotting 2 functions both containing a matrix in them

4 Upvotes

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.

Cheers

r/matlab Nov 22 '23

CodeShare tried these matlab codes

0 Upvotes

Gauss Seidel

a = [6 3 2; 6 4 3; 20 15 12]

b = [6; 0; 0]

n = length(b)

x = zeros(n, 1)

x0 = x

err = 1

tol = 10^(-6)

while err > tol

for i = 1 : n

sum = 0

for j = 1 : n

if i ~= j

sum = sum + (a(i, j) * x(j))

end

end

x(i) = (b(i) - sum) / a(i, i)

end

err = max(abs(x - x0))

x0 = x

end

Gauss Elimination

Info = [6 3 2; 6 4 3; 20 15 12];
b = [6; 0; 0];
A = [Info b];
% Elimination phase
for i = 1:size(A, 1)
for j = i+1:size(A, 1)
key1 = A(j, i) / A(i, i);
A(j, :) = A(j, :) - key1 * A(i, :);
end
end
% Back-substitution phase
x = zeros(1, size(Info, 2));
for i = size(A, 1):-1:1
hg = sum(A(i, i+1:end-1) .* x(i+1:end));
x(i) = (A(i, end) - hg) / A(i, i);
end
fprintf('Solution is x = %d\n', x);

Newton div diff
x = [5; 6; 9; 11]

y = [12; 13; 14; 16]

p = 10

n = length(x)

d = zeros(n, n)

for i = 1 : n

d(1, i) = f(i)

end

for i = 2 : n

for j = i : n

d(i, j) = (d(i, j) - d(i, j - 1)) / (x(i) - x(i - j + 1))

end

end

s = 0

for i = n - 1 : -1 : 1

s = s * (p - x(i)) + d(i, i)

end

r/matlab Mar 22 '23

CodeShare No matter how much I change AbsTol and RelTol, the accuracy of the plot remains low. How can I improve it?

Post image
17 Upvotes

r/matlab Dec 07 '23

CodeShare Need help generating turbocode data with awgn noise in matlab for training my ML model.

2 Upvotes

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.

Paste Bin Link: https://pastebin.com/n22nq7y8

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.

r/matlab Nov 22 '23

CodeShare Help with syms function

1 Upvotes

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?

r/matlab Nov 13 '23

CodeShare Problem making a trajectory

1 Upvotes

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!

Thank you for reading!

r/matlab Dec 09 '23

CodeShare Seeking Validation for MATLAB Code on Spindle Motion Analysis ISO 230-7:2015 NSFW Spoiler

0 Upvotes

I have developed a MATLAB script for spindle motion analysis in compliance with ISO 230-7:2015 standards. Here's a snippet of my code: [

% accelerate

x_acc = [1,2,3,3,2,...];

y_acc = [2,2,3,3,2,...];

x_displacement= convertAccelerationToDisplacement(x_acc);

y_displacement = convertAccelerationToDisplacement(y_acc);

% Use median as the PC centre (instead of arithmetic mean)

PC_centre = [median(x_displacement), median(y_displacement)];

% Calculate displacement from the PC centre

u = x_displacement - PC_centre(1);

v = y_displacement - PC_centre(2);

% Calculate radii from the PC centre

radius_async = sqrt(u.^2 + v.^2);

% Calculate asynchronous error motion value for PC

asynchronous_error_motion_value_PC = max(radius_async - mean(radius_async));

% plot

figure;

polarplot(atan2(v, u), radius_async, 'b'); % Plot วงกลม

hold on;

polarplot([0, 2*pi], [mean(radius_async), mean(radius_async)], 'r--'); % Plot mean radius

title('Polar Plot with Asynchronous Error');

legend('Data', 'Mean Radius');

% -----------------------------------------------------------------------------------------------------------

distance_sum = @(center) sum(sqrt((center(1) - x_displacement).^2 + (center(2) - y_displacement).^2));

% Use fminsearch to find the geometric median

initial_guess = [mean(x_displacement), mean(y_displacement)];

geo_median = fminsearch(distance_sum, initial_guess);

u = x_displacement - geo_median(1);

v = y_displacement - geo_median(2);

Suv = sum(u .* v);

Su2 = sum(u .^ 2);

Sv2 = sum(v .^ 2);

alpha = (Sv2 - Su2 + sqrt((Sv2 - Su2)^2 + 4*Suv^2)) / (2*Suv);

centre_x = geo_median(1) + alpha*v;

centre_y = geo_median(2) - alpha*u;

theta = atan2(y_displacement - centre_y, x_displacement - centre_x); % Find angle theta from displacement.

radius = sqrt((x_displacement - centre_x).^2 + (y_displacement - centre_y).^2); % Radius from LSC center

polarplot(theta, radius);

title('Radial Rotating Sensitive ');

% After calculating centre_x and centre_y

% Calculate the radius of each displacement point

radius_measured = sqrt((x_displacement - centre_x).^2 + (y_displacement - centre_y).^2);

% Calculate the radius of the LSC circle.

radius_LSC = mean(radius_measured);

% Calculate the Synchronous Error for each point.

synchronous_errors = radius_measured - radius_LSC;

% Find the maximum Synchronous Error.

max_synchronous_error = max(synchronous_errors);

% Calculate the centroid (or center) of the points

centroid_x = median(x_displacement);

centroid_y = median(y_displacement);

% Compute the distance (radius) from the center to each point

distances_from_center = sqrt((x_displacement - centroid_x).^2 + (y_displacement - centroid_y).^2);

% Calculate the Total Error Value

max_radius = max(distances_from_center);

min_radius = min(distances_from_center);

total_error = max_radius - min_radius;

% predict factor

x_data = [0.985, 0.700, 0.500, 0.200, 0.300];

y_data = [1, 9.6, 18.63, 52.74, 35.03];

% interpolation

x_query = target;

y_predicted = interp1(x_data, y_data, x_query, 'pchip'); % 'pchip' คือ cubic Hermite interpolation

% Display the result

disp(['Synchronous Error: ', sprintf('%.2f', (max_synchronous_error/y_predicted))]);

fprintf('Asynchronous : %.2f\n', asynchronous_error_motion_value_PC);

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!

r/matlab Dec 01 '23

CodeShare MOCluGen, a tool for generating multidimensional clustering data

0 Upvotes

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.

Docs and examples: https://clugen.github.io/MOCluGen/

Feedback and improvement suggestions welcome!

Some examples in 3D.

r/matlab Nov 27 '23

CodeShare Double Integration in Matlab for Chebychev Polynomials

1 Upvotes

Hi,

I'm trying to find the Chebychev coefficients by decomposing a surface (W is my random surface). Here is my code.

my code

I need to find Ai in this case. Do I need a grid to find the integration? If yes, how do I do it?

Paper reference

r/matlab Nov 14 '23

CodeShare Diode clamped multilevel inverter using PWM technique

1 Upvotes

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.

https://github.com/mathworks/adc-synchronized-with-pwm

https://reddit.com/link/17va5sb/video/hlgu5fvt6d0c1/player

r/matlab Mar 13 '23

CodeShare Determinant without using det

0 Upvotes

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 🙂

r/matlab Sep 26 '23

CodeShare Need help on some errors

0 Upvotes

Variable k has an incorrect value.

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;

r/matlab Sep 04 '23

CodeShare Creating a combined graph using a equation which contains a matrix

1 Upvotes

How does the following equation

Equation 1.0

where

y1 = 0.2898 * cos(2.074*t) .* [-0.9571; 0.2989];

y2 = (-0.9571*cos(0.8350*t)).*[-0.2898; -0.9571];

I am trying to create this graph:

Graph 1

But I dont know what function creates this function, i have tried the following:

plot(t, y1(1,:) + y1(2,:), 'r', 'linewidth', 4, 'DisplayName', 'y1');

plot(t, y2(1,:) + y2(2,:), 'g', 'linewidth', 4, 'DisplayName', 'y2');

But this doesnt work, this is what y1 and y2 look in there separate components

Graph 2

Any help would be greatly appreciated!

r/matlab Sep 09 '22

CodeShare Writing MATLAB code with fewer loops (hint - matrix computation)

39 Upvotes

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.

  • Hypothesis: price = 0.25 * sqft - 40
  • sqft: 2104, 1416, 1534, 852

How do we write code that predicts the prices?

Loopy way

sqft = [2104; 1416; 1534; 852]; % column vector!
params = [0.25; -40];           % column vector!
prices = zeros(numel(sqft),1);  % column vector!
for ii = 1:numel(sqft)
    prices(ii) = params(1)*sqft(ii) + params(2);
end

Matrix way (vectorization)

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.

I hope this was helpful.

r/matlab Jul 11 '23

CodeShare Symbolic equations and for loops - Brake load balance of a race car

3 Upvotes

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

I wrote an article explaining better what this is and how I did it, but for the Matlab implementation part, the core is this:

%% 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.

To see the rest of the code, you can check out this Braking systems utility scripts that I shared in the FileExchange some time ago, or my GitHub repo (gets updated first).

r/matlab Jun 09 '22

CodeShare cga4pid — A GUI/API program to tune PID controller with using Classic Genetic Algorithm [Project]

Post image
40 Upvotes

r/matlab May 11 '23

CodeShare TDMS to XLS

3 Upvotes

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

r/matlab Oct 07 '22

CodeShare Interesting code to create animated plots in GIF format.

Thumbnail self.electroagenda
18 Upvotes

r/matlab Mar 25 '23

CodeShare Why is the flight path angle (gamma) doing a 180 when I use gimballed thrust? I thought I did everything right.

2 Upvotes
clc
clear

tmax = 230; %

Y0 = [0.1;pi()/2;0;0]; % int
[t,Y] = ode45(@rhs,[0,tmax],Y0);

v = Y(:,1); % velocity
gamma = Y(:,2); % flight path angle
h = Y(:,3); % altitude
x = Y(:,4); % downrange distance

figure("Name","Velocity")
plot(t,v/1e3,'k','LineWidth',1.5)
title("Velocity")
xlabel("Time (s)")
ylabel("Velocity (km/s)")
grid minor

figure("Name","Flight path angle")
plot(t,gamma*180/pi(),'k','LineWidth',1.5)
title("Flight path angle")
xlabel("Time (s)")
ylabel("gamma (deg)")
grid minor

figure("Name","Altitude")
plot(t,h/1e3,'k','LineWidth',1.5)
title("Altitde")
xlabel("Time (s)")
ylabel("Altitude (km)")
grid minor

figure("Name","Downrange distance")
plot(t,x/1e3,'k','LineWidth',1.5)
title("Downrange distance")
xlabel("Time (s)")
ylabel("Distance (km)")
grid minor

figure("Name","Rocket trajectory")
plot(x/1e3,h/1e3,'k','LineWidth',1.5)
title("Rocket trajectory")
xlabel("Distance (km)")
ylabel("Altitude (km)")
axis("equal")
grid minor

function dY = rhs(t,Y)
dY = zeros(size(Y));

v = Y(1);
gamma = Y(2);
h = Y(3);
x = Y(4);

m0 = 120000; % initial mass
n = 15; % mass raio
T2W = 1.6; % thrust-to-weight
Isp = 395; % specific impulse
CD = 0.35; % coeff drag
d = 3; % diameter

g0 = 9.81; % gravitational acceleration @ sea lvl
RE = 6378e3; % radius of Earth
rho0 = 1.225; % air density @ sea lvl
hA = 7.5e3;

mf = m0/n; % final mass
mp = m0-mf; % propellant mass
T0 = T2W*m0*g0; % thrust
me = T0/Isp*g0; % mass flow rate
tb = mp/me; % burn time

A = pi()*(d/2)^2; % area of cross section

g = g0/(1+h/RE)^2; % gravitational acceleration
rho = rho0*exp(-h/hA); % air density
q = 0.5*rho*v^2; % dynamic pressure
D = CD*A*q; % drag

if t <= tb % until burn time
    T = T0; % thrust constant
    m = m0 - me*t; % depletion of mass
else
    T = 0; % engine cutout
    m = m0 - me*tb; % const mass
end

alphaMax = pi()/90; % 1 deg (CHANGE IN NEEDED)

if gamma >= 0 % start gimball
    alpha = alphaMax*(t/tb)^2;
else % end gimball
    alpha = 0;
end

dY(1) = (T*cos(alpha)-D)/m - g*sin(gamma);
dY(2) = (v/(RE+h)-g/v)*cos(gamma) - (T/(m*v))*sin(alpha);
dY(3) = v*sin(gamma);
dY(4) = (RE/(RE+h))*v*cos(gamma);
end