/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.
Try saturnapi to share and run MATLAB code in a web browser!
If you want flair simply Message the mods
/r/matlab
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 ;)
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.
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.
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!
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)
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.
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:
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
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
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
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”
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???
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
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
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?
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
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?
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!
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!
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!
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
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?
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?
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 !
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?
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.
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