/r/matlab

Photograph via //r/matlab

Official MATLAB subreddit


MATLAB news, code tips and tricks, questions, and discussion! We are here to help, but won't do your homework or help you pirate software.

The effort you put into asking a question is often matched by the quality of our answers.

r/matlab discord channel


Sort By Topic

    Homework     Technical

    Code Share   News

    Tips             Misc


Places to learn Matlab
Matlab Resources

Try saturnapi to share and run MATLAB code in a web browser!

If you want flair simply Message the mods


/r/matlab

61,677 Subscribers

0

Which AI/LLM are you using or you think delivers best results for MATLAB code?

Which ChatGPT, CodeGPT, Copilot, Gemini are you using to help you write your Matlab functions or scripts? Are the results reliable, in which extend? Are other tools more adapted and especially for producing MATLAB code?

I am interesting in helping me debug and quickly develop my code for my telecommunications oriented scientific research. Should I consider any paid version?

Thanks for your feedback ;)

2 Comments
2024/11/02
22:32 UTC

1

MATLAB/SIMULINK - Electrical Engineer Power System Thesis OLTC/PV Penetration

Hi all! ,

I am a Final Year Electrical Engineering student, and doing my Thesis project.

My topic is Power System Voltage Control by On-Load Tap Changer in Distribution Networks with High Renewable Energy Penetration. Im required to build a working simulation for my topic using Matlab/Simulink.

A little bit about my topic, I'm looking to use a battery energy storage system (BESS) with SOC controllers and a control philosophy / system to help offset voltage sag/swell in the distribution network to reduce the amount of tap changes on the OLTC.

I'm looking specifically for the IEEE 13 bus Feeder system or any alternative to start with that has OLTC supply. Some of the Bus have PV and some don't, I need to integrate Battery system on those PV buses with SOC controllers, so that the battery charges when voltage is too high, and discharge when voltage is too low from grid, and if outside of parameters, controller tells OLTC to tap change, my goal is to lower tap changing operations by using BESS system

I'm wondering if anyone here has this template, know's if it exists within MATLAB already, or knows of how I would go about starting this? I haven't had much experience with matlab and my literature review didn't turn up much practical help through journal articles. Most academics don't seem to like sharing their simulations or even screenshots of block diagrams to start from.

0 Comments
2024/11/02
15:27 UTC

0

Root solver

How would you go about writing a cardano algorithm for when the discriminant is equal to 0? Having a hard executing/writing this code as its not very clear online or class notes how to actually execute it.

0 Comments
2024/11/02
15:16 UTC

1

Light distribution modeling in Matlab?

I (Engineering and math background) am designing a photobioreactor. I am looking for a simple (does not have to have very high resolution) way to quickly calculate light density inside a space from multiple light sources.

I only need a 2D graph/visualization of light distribution in say for example a 1 meter by 1 meter square, with about 12-16 light sources, all with known angles and irradiance. The goal is to be able to change variables like the light positioning and quantity of lights, or the attenuation due to media (air vs water vs algae filled water, etc.) in the model easily to make comparisons. Does anyone know a method to do this in Matlab? I've done something similar before for 2D temperature gradient in a solid, but those models are a bit easier because you only have a single equation of diffusion for adjacent particles/packets. In my case I need a given packet/space to be able to take information from multiple sources, corresponding to their distance.

I don't have any expensive physics modeling software right now. I've done these calculations before for a single design by hand, but do not want to do it 100 times...Thank you!

0 Comments
2024/11/02
13:58 UTC

1

Issue with publishing graphs :(

Hello, I have never posted to reddit, but I have tried searching for an answer to my issue and have yet to see someone with a similar problem. My issue is with getting graphs to publish. I use 'figure' for each graph, AND my professor can publish my code with her computer and the graphs will publish just fine. When I run my code, the graphs all work the way they should, no issues there, but when I go to publish, it will open a blank figure as the first figure. I know that is what's causing everything after to not publish.

I am updated to the latest version, so that is not the issue. I have no clue if this is a matlab issue or an issue with my laptop or maybe my files? If anyone is able to point me in the right direction that would be super helpful, because I hate losing points on assignments over this, and this problem has only started recently, I used to be able to publish figures no problem...

thanks in advance (and I'm sorry if I posted this in the wrong tag thing)

1 Comment
2024/11/02
03:45 UTC

22

MATLAB and Python - Advantages of using them together.

Greetings. I have a standard question that I know has been asked here in one form or another, so I'll preface by saying I've been in the midst of doing research, including perusing some posts here and in r/python . I've been a systems engineer for decades and have been self teaching myself python. I'm at the point where I;m just learning OOP (classes and objects) but have been coding a personal project to apply what I've been learning along the way. For context, it's the second version of code that calculates the maximum altitude and peak velocity of a low power model rocket as it reaches engine burnout. I've always been interesting in learning MATLAB but never had the opportunity to use it for my daily work. I do know that MATLAB can call Python scripts so my question is what are some advantages of using MATLAB along side Python? The little I've seen so far leads me to believe that using Pandas, Numpy, and similar would allow me to do in Python alone what MATLAB can do. I'm considering taking the MATLAB Onramp Course to get up to speed. Thanks for making it this far, all opinions are welcome.

28 Comments
2024/11/02
03:00 UTC

2

Several fancy functions

Hi everyone, I wrote several fancy functions that may help your coding experience, since they are in very early developing stage, I will be thankful if anyone could try them and give some feedbacks. Currently I have following:

  • fstr: a Python f-string like expression
  • printf: an easy to use fprintf function, accepts multiple arguments with seperator, end string control.

I will bring more functions or packages like logger when I am available.The code is open sourced at GitHub with simple examples: https://github.com/bentrainer/MMGA

0 Comments
2024/11/02
00:26 UTC

4

Some questions about a 100% work using MATLAB

I work as electronic engineer for an international company, mostly on motor control, and I can't say to spend 100% of my working hour in MATLAB, I have a lot of other annoying stuff, let's say 20% of my work time is for MATLAB.

Just curios:

- do you work 100% of the time in MATLAB? Full remote or in the company office?

- how did you find this job/what did you search over linkedin or recruiters aggregators?

- is there some full remote options for a MATLAB coder o model based designer?

Thank you so much

9 Comments
2024/11/01
19:27 UTC

7

Is my professor wrong?

Problem

My matlab code

I'm pretty confident on my answer on this one but my professor marked this one wrong. ODE45 should be fairly a straight forward answer.

Here is my matlab code copy paste:

clear; clc; close all;

 

% Define the differential equation

dydt = @(t, y) 5 * (y - t^2);

 

% Set the initial condition and time span

y0 = 0.08;

tspan = [0 5];

 

% Solve the differential equation using ode45

[t, y] = ode45(dydt, tspan, y0);

 

% Plot the result

plot(t, y, 'b-', 'LineWidth', 1.5)

xlabel('Time (t)')

ylabel('Solution y(t)')

title('Solution of dy/dt = 5(y - t^2) using ode45')

grid on

8 Comments
2024/11/01
17:07 UTC

0

Tidal Prism

Hey y’all. Please, I am supposed to calculate tidal prism using Matlab but I would really love to have a fundamental knowledge of what I am to do. I would really appreciate any resource on tidal prism calculation or tidal prism dynamics as this would build a foundation for my Matlab codes. I have checked YouTube and there isn’t much calculation on there. Or it is just maybe the fact that I am not typing the right things on the search engines. I usually type “Tidal prism 101” or “Tidal Prism concepts and calculations”

0 Comments
2024/11/01
13:47 UTC

2

Scatter plot with table next to it and saving together as single image, help please.

Hello.

I am really struggling here. I am trying to have a scatter plot and information about each point in a table next to it, and then save it together as one image.

Using version 2020b.

I have attempted multiple methods to construct it. Finally I have it constructed but it won't save.

Here is how I basically constructed the figure:
gcf = uifigure;

g = uigridlayout( gcf, [1,2]);

Splot = uiaxes(g);

hold(Splot, 'on');

p = scatter(Splot, x-data, y-data);
gT = uitable(g, 'Data', data);

This forms close to what I am looking for, although still needs tweaking. However I can't save the damn thing. I've tried

exportgraphics(gcf); but this will give me a blank white png.

exportgraphics(g); but this just gives me the scatter plot.

saveas(gcf, "My Data.png") but this gives me errors.

exportapp(gcf) but this just gives me errors or a blank file.

I have also tried using just figure, instead of uifigure, but the table always covers the plot and then also won't save the table with the plot as an image.

How the heck can I export this as an image? I am also open to an alternative method that I couldn't figure out. I've been reading and trying different things for about 8 hours now.

***Edited to add***

Manually typing into the terminal the following command will work.

exportapp(gcf, "name.png");

However if that same line is in my script, only the scatter plot will render in the image and the table section will be blank. Anyone have any idea why???

2 Comments
2024/10/31
22:18 UTC

16

Peak detection in noisy signal

How can I automatically detect the marked peaks and ignore the noise, currently I use 'findpeaks' with the settings 'MinPeakProminence' and 'MinPeakDistance'

Thanks in advance

18 Comments
2024/10/31
18:11 UTC

0

Matlab binary image array

Hi, Im a mech eng student and we’ve been given a matlab task on binary arrays, we need to make an image that has various triangles and squares, and I can’t seem to get the last one, was wondering if anyone could help, I have done most the code it’s literally one line that I can’t figure out, it is the code for the bottom right triangle, it is supposed to be that exact size except the other way round, so the gradient is positive rather than negative

2 Comments
2024/10/31
18:02 UTC

1

is power converters fitting in model linearization

I'm making an inverter model with feedback to control the duty cycle on an RL load, is it possible to get a transfer function with an easy way to design the controller based on it?

3 Comments
2024/10/31
17:59 UTC

1

DFIG-WT Slow simulation in Simulink, can anyone help

3 Comments
2024/10/31
16:55 UTC

1

the iteration in this code can not produce out puts, need some help

function triangular_v()

response = input('Does the triangular section have vertical walls (enter "yes" or "no"): ', 's');

B = input('Enter the top width of the channel: ', 's');

ang = input('Enter the horizontal angle of the channel: ', 's');

m = input('Enter the side slope (1:m) of channel (value of m needed): ', 's');

H = input('Enter the total height of the triangular part of channel: ', 's');

q = input('Enter the discharge of the channel: ', 's');

n = input('Enter Manning coefficient: ', 's');

s = input('Enter the channel (stream-wise) slope: ', 's');

hn = input('Enter the depth flow in the channel: ', 's');

g = 9.81; % Acceleration due to gravity (m/s²)

% Initialize variables

m = str2double(m);

H = str2double(H);

q = str2double(q);

n = str2double(n);

s = str2double(s);

B = str2double(B);

% Calculate side slope if not provided

if isempty(m) && ~isempty(ang)

ang = str2double(ang);

m = 1 / tan(deg2rad(ang)); % Convert angle to radians

elseif isempty(m) && ~isempty(B) && ~isempty(H)

m = (B / 2) / H; % Assuming vertical walls to calculate m

end

% Case for vertical walls

if strcmpi(response, 'yes')

n = str2double(n);

s = str2double(s);

q = str2double(q);

A = m * (H ^ 2);

p = 2 * H * sqrt(1 + m ^ 2);

qn = ((A ^ (5 / 3)) * (s ^ (1 / 2))) / (n * (p ^ (2 / 3)));

if q <= qn

% Calculate normal depth

cont = true;

h = 1; % Initial guess for iteration

while cont

hn = ((q * n * (2 * h * sqrt(1 + m^2)) ^ (2 / 3)) / ((s ^ (1 / 2)) * (m * h) ^ (5 / 3))) ^ (3 / 5);

e = abs(hn - h);

if e < 0.0005

cont = false;

else

h = hn;

end

end

% Calculate Froude number at normal depth

A = hn * (m * hn);

v = q / A;

B = 2 * m * hn;

Dm = A / B;

Fr = v / sqrt(g * Dm);

% Calculate critical depth

hc = ((2 * q^2) / ((m^2) * g)) ^ (1 / 5);

fprintf('The Froude number for corresponding normal depth is %.4f and the critical depth is %.4f\n', Fr, hc);

else % Case for q > qn

B = 2 * m * H;

y = 0;

cont = true;

while cont

q1 = (((m * H ^ 2 + (B * y)) ^ (5 / 3)) * (s ^ (1 / 2))) / (n * (2 * y + (2 * H * sqrt(1 + m^2))) ^ (2 / 3));

e = abs(q - q1);

if e > 0.0005

y += 0.0001; % Increment for iteration

else

cont = false;

end

end

hn = H + y;

fprintf('The normal depth is %.4fm\n', hn);

% Calculate Froude number and critical depth

hc = ((2 * q^2) / ((m^2) * g)) ^ (1 / 5);

fprintf('The critical depth is %.4f\n', hc);

% Froude number for normal depth

A = H * (m * H) + 2 * y * m * H;

v = q / A;

B = 2 * m * H;

Dm = A / B;

Fr = v / sqrt(g * Dm);

fprintf('The Froude number for the normal depth is %.4f\n', Fr);

end

elseif strcmpi(response, 'no')

% Process for non-vertical walls

if ~isempty(n) && ~isempty(s) && ~isempty(q)

h = 1; % Initial guess

cont = true;

while cont

hn = ((q * n * (2 * h * sqrt(1 + m^2)) ^ (2 / 3)) / ((s ^ (1 / 2)) * (m * h) ^ (5 / 3))) ^ (3 / 5);

e = abs(hn - h);

if e < 0.0005

cont = false;

else

h = hn;

end

end

fprintf('The normal depth is %.4fm\n', hn);

% Calculate Froude number

A = hn * (m * hn);

v = q / A;

B = 2 * m * hn;

Dm = A / B;

Fr = v / sqrt(g * Dm);

fprintf('The Froude number for corresponding normal depth is %.4f\n', Fr);

end

% Calculate critical depth

hc = ((2 * q^2) / ((m^2) * g)) ^ (1 / 5);

fprintf('The critical depth is %.4f\n', hc);

else

fprintf('The input you entered regarding whether there are vertical walls or not is invalid.\n');

end

end

2 Comments
2024/10/31
14:14 UTC

1

So i am trying to fit a curve graph, theres supposed to be a curvefitter app but i cant find it. What is the problem here, how do i do this?

6 Comments
2024/10/31
09:31 UTC

0

help with appdesigner

I passed to another pc an app designer file through whatsapp, but when i downloaded it in the other pc it downloads as a zip, and i dont find a way to open it in matlab, any help?

1 Comment
2024/10/31
00:22 UTC

0

Help Needed: Simulating two-phase PMLSM in Matlab/Simulink

Hi everyone, I'm currently working on a project involving a two-phase linear tubular synchronous motor from Linmot and their associated drive.

I’ve been searching for solutions for weeks but haven’t found a suitable approach to model this motor in MATLAB Simscape, which predominantly supports three-phase motors.

I've looked into various resources and forums but haven’t found a workaround or a custom block that fits my needs. If anyone has experience with modeling two-phase motors or can point me towards useful resources or tips, I would greatly appreciate it!

1 Comment
2024/10/30
21:33 UTC

0

Need a fast solution to interpolation during simulation

Hi all,

I have a mechanical system I’m solving with ode15s in Matlab. Within my model, I have parameters that are a function of some state variable within the simulation, and this is represented with a look up table. However, just having a quick go with interp1, linear, it has significantly slowed down my simulation. This is a bit of an issue as I will have to introduce many more of these, but at this rate it’s a no go. Has anyone got experience with a similar problem and found any alternatives?

Appreciate any help!

5 Comments
2024/10/30
19:03 UTC

2

CC4M - Code Checker for MATLAB update

0 Comments
2024/10/30
15:21 UTC

1

Plotting Data From an Excel Spreadsheet

Hi, I have been tasked with creating a Matlab script which can extract data from a Excel spreadsheet. The script must extract the time data as the x value with the y value being assigned to the force data. I am able to do this, however, there are 4 different tests that were ran and all the data is compiled together. The excel spreadsheet has another column with the test number i.e 1-4. How can I get the script to extract this data, assort the time and force data into the correct test number and make an individual plot for each test.

Hope this makes sense!

5 Comments
2024/10/30
14:52 UTC

2

Millisecond Date TimeFormat

I have an imported data set with 7 digit millisecond data. (1230000) the first three digits are the milliseconds and the remainder are placeholders for some reason. If i classify the column with format SSSSSSS it imports the information as NaT. I'm not finding the right instructions to get MatLab to recognize the data correctly. I modified the data to a decimal .123 but now I can not alter from a number to date time. Anyone with some advice, recommendations would be appreciated.

Update: I figured it out.

I have table with the following Date Time SubSec 20241009. 230003. 6840000

I used the milliseconds formula to convert the variable SubSec

2 Comments
2024/10/30
09:58 UTC

1

Traditional Bowling Help

I’m trying to code a traditional bowling game for my Matlab class and was given the pseudocode to do so. The rules are weird and unfortunately this pseudocode is even weirder. Could anyone help explain it in an easier way?

2 Comments
2024/10/29
23:42 UTC

1

Test Sequence block not found

I have created test harness out of one model, with test sequence block. After it I copied test cases from other harness test manager, run it and got the error Test Sequence block is not found. But I see that it tries to reference the Test Sequence block of the harness from which I copied test cases, how to fix that?

0 Comments
2024/10/29
22:55 UTC

1

Compression of spectrogram when changing sampling rate

Hello all,

I stumbled upon a phenomenon that is boggling my mind, which I have not experienced before when playing with signals (probably because I always did it along regulated company guidelines).

For a personal research project, I have instrumented a system with sensors. Importantly, I am recording current draw coming out of the power outlet with an amp clamp, connected to an arduino. The samples are acquired at a 750Hz sampling rate. Power in my country is delivered at 50Hz - AC. Going that high in acquisition rate was motivated by the Nyquist frequency theorem.

Now the set-up for the question: I use the signal analyser app directly to have a preview of the Fourier Transform and Spectrogram. Surprise, surprise, the spectrogram shows a frequency band at 39Hz and harmonics (somehow only the odd multiple harmonics). I was expecting to see 50Hz, 100Hz, 150Hz ...

Question 1: Any idea why is that ?

Secondly, I started playing with the sampling rate parameter. Turns out that if I go lower, I compress the frequency bands (they get closer) until creating aliasing when going under Nyquist Frequency. If I increase the sampling rate, the opposite happens.

Question 2: Is there a specificity of Discrete Fourier Transform or Short Time Fourier Transform I am not aware of in its use on Matlab ?

Cheers !

5 Comments
2024/10/29
21:41 UTC

2

How to simulate GPS with SBAS Correction fused with Odometer data

Let's assume I have a user or vehicle moving in a straight line. I have to estimate its position using GPS and the odometer information and write a batch filter/Kalman filter code. I also have to implement SBAS correction to the GPS position estimate. I have some confusion.

I don't have any actual data at this point. How can I simulate sensor measurement in Matlab? I am not sure how to proceed with this problem. I can write code to estimate the position from the GPS receiver data available on the internet using linearized pseudorange equations. Still, I don't have the same user's odometer sensor data, so I am unsure how to approach this problem. Anybody can help?

0 Comments
2024/10/29
20:21 UTC

1

Help window out of browser

Hi,

I've just changed my PC and reinstalled the latest Matlab version (R2024b). However, I cannot open the documentation in a separate window. Now it keeps opening it in my web browser which I really do not like because I wish to keep things separated.

On my previous PC and my professional PC it works just fine.

Please help me, I cannot find anything.

Example from https://www.youtube.com/watch?v=YB_3Bx6URx8

5 Comments
2024/10/29
19:22 UTC

0

is there anyone I can dm about a homework question

I have an assignment Ive been working on for more than a week and it is not working, I desperately need help. SOMEONE PLS HELP

6 Comments
2024/10/29
18:29 UTC

Back To Top