/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
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.
i have checked with audio files its giving noise and vibration channels but when i checked known audio file which has total 11 channels and mine is giving total 24also the pascal to dB scale for noise in 1/3rd octave is not correct and the rms values are wrong
There doesn’t seem to be directional control valves options other than a check valve for 2-phase fluids. I’m looking for a 4/3 or 4/2 DCV in the context of simulating a simple reversible heat pump. Am I overlooking something? Are you able to create a custom block? Should I use controllable flow restrictions as a work around? Thanks
Hey everyone, I am trying to transition from using structure based ‘containers’ of data to custom classes of data, and ran into a bit of a pickle.
I have a whole bunch of parameters, and each parameter has both a data vector and properties associated with it. I store the data and properties as individual variables within a single mat file per parameter. This allows me to assign that mat file to a variable when loading it in a workspace, and gives it a structure formatting, where each field is a property of that parameter. This makes the mat file the property ‘object’ in essence, and the variables within, its properties.
To provide more infrastructure to the system (and force myself to get exposure in OOP) I am trying to switch to using a custom ‘Param’ class, that has its associated properties and data vector. In doing so, I lose the ability to loop through parameters to load and analyze, because each parameter file contains its own discreet object. This breaks a lot of tools I have already built, that rely on being able to just assign whatever variable name I want to the parameter properties while I’m doing analysis.
For example, I have a parameter, ‘Speed.mat’, that has a property ‘Units’ with a value of ‘mph’ and a time history based data vector. Before, I could do: myVar = load(‘speed.mat’); And myVar would then be a struct with the fields ‘Units’=‘mph’ and ‘data’ = (:,1) timetable. I can index directly into ‘myVar.data’ for calculations and comparisons through all of my tools. Now though, I have an object ‘Speed’ that gets saved in the ‘Speed.mat’ file. When loading this file I will always get either the variable ‘Speed’ or a struct containing this variable. I have played around with the saveobj and loadobj methods, but those do not solve my problem of having a discreetly named object each time.
I’m sure I must be making some huge paradigm mistake here, and was hoping for advice on how I could adapt this process while making minimal changes to my current infrastructure. I apologize that it’s wordy, I will do my best to clarify further in the comments!
I hút finished the EDG programming challenge and until I found out that for the coding part, I just need to complete either the matlab section or the algorithm section. However I did both, but the algorithm section I didnt do ưell, compare to the matlab section. So is the recruiter gonna skip my bad part and review the matlab section only…
Hi everyone,
I am trying to simulate a circuit and the circuit throws error saying the diode is open circuited and inductor is open.
Now, the other side of inductor is shorted using LC circuit. The flux buildup in the core is understood. How can I avoid this error. Any suggestions is appreciated.