/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
Our MathWorks Usability Team is working on an accessibility project and they want to interview people who use MATLAB and also have experience with screen readers. If you fit the criteria and are interested, sign up here https://www.mathworks.com/products/usability.html?tfa_30=A11Y
Check out our latest release of Onramp courses, which include updated versions of Machine Learning and Deep Learning courses. Onramps are free to all.
Note: Deep Learning courses now use the dlnetwork workflow, such as the trainnet function, which became the preferred method for creating and training deep networks in R2024a. I will check it out personally to learn the new way.
There are also new short courses and learning paths, which require subscription, which may be already included in your license.
I have a matlab code for channel detection for noise and vibration , in my code total number channel detection is correct for all audio file the issue is coming when separating the noise and vibration channels , after detection only I will perform fft and 1/3 rd octave and lastly rms values are also not correct , when I will do fft and octave , the noise channel will convert to db and vibration will be in g
I’m encountering a persistent issue with MATLAB. Even though my main code is correct, I keep getting random pop up errors. To troubleshoot, I tried running a very simple script, but I still get these weird unrelated pop up errors. Now, every time I run any code, an error pop-up appears. This is really concerning since my final projects are approaching, and I can’t afford for MATLAB to be unreliable. I’d really appreciate your help in resolving this
see title
String theory
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import CubicSpline
class UnifiedStringTheorySimulator: """ A comprehensive simulator of multidimensional vibrating strings, incorporating higher-dimensional vibrations, compactification, supersymmetry, energy quantization, cubic smoothing, and dynamic interactions. """
def __init__(self, dimensions=6, n_modes=7, length=1.0, compactification_period=1.0):
"""
Initialize the string simulator with enhanced features.
Parameters:
- dimensions (int): Number of spatial dimensions (including compactified ones).
- n_modes (int): Number of vibration modes to simulate.
- length (float): Length of the string.
- compactification_period (float): The periodicity of the compactified extra dimensions.
"""
self.dimensions = dimensions
self.n_modes = n_modes
self.length = length
self.x = np.linspace(0, length, 500)
self.compactification_period = compactification_period
def vibrate(self, mode, dimension):
frequency = mode * np.pi / self.length
phase_shift = dimension * np.pi / 4
return np.sin(frequency * self.x + phase_shift)
def compactify_dimension(self):
"""
Simulate compactification of a dimension as a toroidal geometry.
"""
theta = np.linspace(0, 2 * np.pi, 500)
phi = np.linspace(0, 2 * np.pi, 500)
theta, phi = np.meshgrid(theta, phi)
R = 1 # Major radius of the torus
r = 0.5 # Minor radius of the torus
x = (R + r * np.cos(phi)) * np.cos(theta)
y = (R + r * np.cos(phi)) * np.sin(theta)
z = r * np.sin(phi)
return x, y, z
def superposition(self):
vibration_sum = np.zeros_like(self.x)
for dim in range(1, self.dimensions + 1):
for mode in range(1, self.n_modes + 1):
vibration_sum += self.vibrate(mode, dim)
return vibration_sum
def supersymmetric_modes(self):
"""
Generate supersymmetric partners with alternating signs for each mode.
"""
fermionic_vibrations = []
for dim in range(1, self.dimensions + 1):
for mode in range(1, self.n_modes + 1):
fermionic_vibrations.append((-1) ** mode * self.vibrate(mode, dim))
return fermionic_vibrations
def quantized_energy(self):
"""
Calculate quantized energy levels, incorporating a simplified relativistic model.
"""
return np.array([np.sqrt((mode * np.pi / self.length) ** 2 + 1) for mode in range(1, self.n_modes + 1)])
def gravitational_effect(self):
"""
Simulate a gravitational potential induced by the vibrating string.
"""
return np.exp(-self.x / self.length)
def cubic_smooth_superposition(self):
"""
Apply cubic spline smoothing for a more continuous representation.
"""
superposition_vibration = self.superposition()
cubic_spline = CubicSpline(self.x, superposition_vibration)
smooth_x = np.linspace(self.x[0], self.x[-1], 2000)
smooth_vibration = cubic_spline(smooth_x)
return smooth_x, smooth_vibration
def string_interaction(self, split_probability=0.1):
"""
Simulate dynamic string interactions with potential splitting.
"""
if np.random.rand() < split_probability:
new_length = self.length / 2
return [
UnifiedStringTheorySimulator(self.dimensions, self.n_modes, new_length, self.compactification_period),
UnifiedStringTheorySimulator(self.dimensions, self.n_modes, new_length, self.compactification_period),
]
return [self]
def plot_torus(self):
"""
Visualize compactified dimensions on a toroidal surface.
"""
x, y, z = self.compactify_dimension()
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap='viridis', edgecolor='none', alpha=0.8)
ax.set_title("Compactified Dimension (Torus)")
plt.show()
def plot_results_with_smoothing(self):
"""
Visualize vibrations, quantized energy levels, and gravitational effects.
"""
superposition_vibration = self.superposition()
smooth_x, smooth_vibration = self.cubic_smooth_superposition()
energies = self.quantized_energy()
potential = self.gravitational_effect()
plt.figure(figsize=(12, 12))
# Plot vibrations
plt.subplot(3, 1, 1)
plt.plot(self.x, superposition_vibration, label="Original Superposition", alpha=0.6)
plt.plot(smooth_x, smooth_vibration, label="Cubic Smoothed Superposition", linewidth=2)
plt.title("String Vibrations with Smoothing")
plt.xlabel("Position")
plt.ylabel("Amplitude")
plt.legend()
# Plot energy levels
plt.subplot(3, 1, 2)
plt.bar(range(1, self.n_modes + 1), energies, color="skyblue", label="Relativistic Energy")
plt.title("Quantized Energy Levels")
plt.xlabel("Mode")
plt.ylabel("Energy")
plt.legend()
Can you run the above code for completed string theory # Plot gravitational effects plt.subplot(3, 1, 3) plt.plot(self.x, potential, label="Gravitational Potential", color="green") plt.title("Gravitational Effects") plt.xlabel("Position") plt.ylabel("Potential") plt.legend()
plt.tight_layout()
plt.show()
simulator = UnifiedStringTheorySimulator(dimensions=6, n_modes=7, length=1.0, compactification_period=1.0) simulator.plot_torus() simulator.plot_results_with_smoothing()
Hello!
I need for an application to model a saturable reactor, which can change the reactance based on the control current that I provide from a 3 phase controlled thyristor rectifier. I already did the rectifier bridge, I just need an idea of how to implement a variable reactance based on the B-H hysteresis loop.
I was thinking that maybe I can export the data for the DC voltage and DC current from the rectifier output in simulink and get it into matlab so I can implement the equations that describe the Saturable reactor in matlab, but then I need the values of the reactance back in simulink...
Any ideas of how to do it?
Hi everyone, I am trying to model a rocket in Simulink, and I have the position and orientation as an output from my simulink model, the model is using a PID controller that I have implemented for thrust vector control. Is there anyway to represent the model in the mechanics visualiser (with accurate orientations and positions) over its flight duration? I have downloaded and looked at the BPS.space rocket model from matlab but i am having some trouble with getting an accurate visualisation as if i use a CAD file the moments of inertia are automatically set. Basically I just want to use the mechanics visualiser by inputting all my own values for position and orientation.
I'm using the Instrumentation Control Toolbox and for now I'm just looking to send one number to the serial port every 10ms, which I am then receiving on an Arduino (Serial Receive block is also part of the model but I'm not using it for this).
My model looks like this right now and when I run the simulation it sends a message every time I change the number in the Constant box. I'm looking for a way to send this number every 10ms regardless of if it has changed or not but can't seem to find a way.
This is what my solver setting are set up to
Thanks.
I have had an issue integrating matlab and comsol. Can someone help me do this? I have both codes ready.
Can someone point me in the right direction? I got a bingo game. like a 3x3 grid. I want to code something to change the color of a label once the value is taken. Like if they get a 5 it will change the label to being green. I also want this linked to the Color Change Feature, so like two people right? So if one person selects red as a color then the board will change the values to red as the game goes on. Is this possible to code? Anyone have a video or tutorial? It’d be most appreciated, thanks!
I am attempting a simulation of transient modal propagation of a signal in a cylindrical waveguide involving calculating the transmission loss at each point in the calculation domain. The transmission loss pattern must be calculated and saved at all locations for each frequency in the DFT of the signal. However this would require too much RAM. I would like to store the transmission loss data in a tall array of range x height x frequency using the .mat format, along with the DFT frequencies, however I am unable to initialize the transmission loss array due to size limits. Does anyone know how to do this? Or is anyone aware of threads here or elsewhere discussing the topic?
For clarification, I want to save the full set of transmission loss patterns so as to model the propagation for multiple signals (e.g. LFM, exponential pulse, arbitrary) using the same DFT without recalculating the transmission loss.
Version is R2023a using parallel and signal processing toolboxes.
I want to find the intersection of 2 lines, and plot a horizontal dashed line from the intersection point to the y-axis. Context: finding yield stress on a stress strain graph, and the intersection is between the stress strain curve and the 0.2% offset line. I downloaded this: https://uk.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections?s_tid=FX_rc1_behav , but when I try to use the y coordinate of the intersection, it says 'Index in position 2 exceeds array bounds'. There's definitely 1 (and only 1) intersection by looking visually. How can I find the intersection? Code is copied below:
%Stress-Strain graph for Aluminium
figure(1);
Al_RawData = csvread ('Failure_Al.csv', 2, 0);
Al_Displacement = Al_RawData (:, 2);
Al_Strain = Al_Displacement/Al_G_Length;
Al_Load = Al_RawData (:, 3);Al_Area = pi*(0.0025)^2;
[maxAl_Stress, idx_max] = max(Al_Stress);
peakAl_Strain = Al_Strain(idx_max);
linear_region = Al_Strain < 0.035;
p = polyfit(Al_Strain(linear_region), Al_Stress(linear_region), 1);
intersection = InterX([Al_Strain + 0.002;p(1) * Al_Strain],[Al_Strain;Al_Stress]);
yield_stress = intersection(2,1);
plot (Al_Strain, Al_Stress)
Al_mdl = fitlm (Al_Strain, Al_Stress, 'Intercept', false)
hold on;
plot([peakAl_Strain, peakAl_Strain], [0, maxAl_Stress], '--r', 'LineWidth', 1);
plot([0, peakAl_Strain], [maxAl_Stress, maxAl_Stress], '--r', 'LineWidth', 1);
disp(['Ultimate Stress: ', num2str(maxAl_Stress)]);
disp(['Strain at Ultimate Stress: ', num2str(peakAl_Strain)]);
plot([0, max(Al_Strain)], [yield_stress, yield_stress], '--m', 'LineWidth', 1);
hold off;
I want to find the 1Soltech 15TH-215-P IN MATLAB r2022b I can not find it what can I do?
Hello everyone I finished simulink onramp and I don't know what 's next could someone recommend a youtube course or some projects to learn more
Hello, I am currently studying GPS LNAV messages, and I am generating a custom LNAV GPS navigation message with the SATCOM toolbox
I am using MATLAB R2024b
I've encountered this problem withing the
GPSWaveFormGeneratorExample.mlx,
function "lnavConfig = HelperGPSNavigationConfig(...)",
where, only for some cases, the navigation message bits are not set as expected, for example, here i set ArgumentOfPerigee (omega en the GPS standard) as -2.2406, but when I read the binary file I see a different number
I checked the "HelperGPSNAVEncode.m" file, and I see it saves it this way
So I tried to replicate conversion to binary I did it with this code
function y = num2bits(x,n,s)
% Convert integers to bits by scaling the input integer
%
% Inputs:
% x - Integer that needs to be converted to bits
% n - Number of bits into which the integer must be converted
% s - Scale factor
%
% Output:
% y - Bits vector
y = int2bit(round(x./s),n);
end
clc
num = -2.24059194743000;
n = 32;
s = 2^(-31);
binaryArray = num2bits(num,n,s);
fprintf('\nbinaryArray: [%s]\n', join(string(binaryArray), ','));
decimalNumber = 0;
n = length(binaryArray);
for i = 1:n
decimalNumber = decimalNumber + binaryArray(i) * 2^(n-i);
end
if binaryArray(1)
decimalNumber = decimalNumber - ( 2 ^ n );
end
decimalNumber = decimalNumber * s;
fprintf("El numero original era: %f\n",decimalNumber);
And the output is also different, but weirdly, just 10 times smaller than the expected amount
Thank you
Hi all,
I am starting with a research project and I have to chose laptop for my work. I am choosing between Thinkpad P14s with Ryzen 7 and Windows11 or Macbook Pro with M4 Pro chip. My question is - which machine will run MATLAB better? I heard that Matlab is better optimized for Mac OS.
I will mainly use MATLAB for my work, probably run lots of optimization algorithms like LP/QP.
I have a project and I am just new to matlab. I am searching for a step by step procedure in youtube but I can't find any. After I export the trained model, how can I test another samples? I tried something but there's always an error huhu. Help me please!!!
Is there a web/book Calculus course I can follow getting benefit of this toolbox? I’m a prof Christopher Lum video follower, but I need more example on MATLAB to understand this videos series:
https://youtu.be/haJVEtLN6-k?si=kvB7uJ_Hnsx4JbXA
I’m also watching these great videos, but I really need some livescript to trick to really understand the lectures:
When i try plotting a legend i end up with only the names of the curves. But when i change the type of line of my curves like if i put . or o, it is showing on my graph but not for a continuous line. i tried a few different way to put the legend, manually or just trusting matlab but it doesn't work.Here's my codea_1 = plot(X_1,Y_1, 'b-', 'DisplayName', "Onde incidente");hold on ;a_2 = plot(X_2, Y_2,'r-', 'DisplayName', "Onde transmise");title("Signal experimental Mousse G");legend show;xlabel("temps (s)");ylabel("amplitude");
Hello guys, I'm pretty new to CAD and Simulink, I have been working on a fun project in which I designed a simple AutoCAD model for a robotic arm, and I have been trying to import it to Simulink from AutoCAD, but seems like Simulink multibody can only import XML file but not STP or STL file, unfortunately AutoCAD does not have a feature to export the model as XML file, but I have also tried to import that using STP and use the model as file solid in Simulink , But I can't figure it out , can anybody please help.
Could you suggest a way to adjust the output range when using CORDIC for division? I am using CORDIC for division with 13 iterations and X = 2, Y = 20. The expected result should be 10, but when I use CORDIC, the output is 1.999. What should I do to get a result closer to the expected value?
Given an nxn diagonally dominant matrix A, and nx1 right hand matrix b, calculate unknown variable vector x using the Gauss-Seidel method.
The problem im having is that i must use the matrix form equation and loop it until it reaches convergance, however the equation i am given doesnt work.
I have gotten L, D, and U of matrix A with:
L = tril(A,-1) D = diag(diag(A)) U = triu(A,+1)
and the matrix form equation for the gauss seidel method i am given is:
(L+D)^-1 [b - Ux] = x
Plugging this equation into a for loop nets me an x vector full of NaN.
I have two days left to my deadline and this is the last thing i need to do but i am completely stumped here and 100% sure its something stupid so if anyone has any ideas on where i've gone wrong i would be incredibly grateful.
I am trying to do this question but the system block I cannot get to work as my code is not level - 2 , as Im trying to keep RL at 50W, any ideas or better methods.
Ciao a tutti,
sono una studentessa magistrale all'università di Padova e cerco aiuto con una parte di codice in cui mi sono bloccata.