/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

62,476 Subscribers

1

Completed String Theory

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()

Run the enhanced simulation

simulator = UnifiedStringTheorySimulator(dimensions=6, n_modes=7, length=1.0, compactification_period=1.0) simulator.plot_torus() simulator.plot_results_with_smoothing()

1 Comment
2024/12/02
19:26 UTC

1

How do I model a saturable reactor in matlab/simulink?

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?

0 Comments
2024/12/02
18:54 UTC

2

Visual of a plane in simscape

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.

0 Comments
2024/12/02
17:05 UTC

2

Sending a message to serial port in fixed time intervals in Simulink

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

https://preview.redd.it/1dq7vbq8of4e1.png?width=836&format=png&auto=webp&s=99ab453a69c639792f6913ec23ef401a6e1ea193

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.

https://preview.redd.it/mwvn8abepf4e1.png?width=1170&format=png&auto=webp&s=e50a5969631fe3d2eab43bb8274ca7b5e4efa92e

This is what my solver setting are set up to

Thanks.

1 Comment
2024/12/02
13:07 UTC

1

Integrating matlab with comsol

I have had an issue integrating matlab and comsol. Can someone help me do this? I have both codes ready.

9 Comments
2024/12/02
12:26 UTC

1

Code to change label color within app designer

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!

0 Comments
2024/12/02
08:00 UTC

3

Initializing empty tall arrays for storage of simulated data

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.

2 Comments
2024/12/02
06:54 UTC

3

Intersection of 2 lines

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:

https://preview.redd.it/cxp8k3ifra4e1.png?width=1775&format=png&auto=webp&s=2f58df5dbbe273389c7791c62d2ac88c36dca1b9

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

2 Comments
2024/12/01
20:29 UTC

0

hello

I want to find the 1Soltech 15TH-215-P IN MATLAB r2022b I can not find it what can I do?

0 Comments
2024/12/01
20:29 UTC

1

How to learn simulink

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

6 Comments
2024/11/30
22:44 UTC

1

MATLAB SATCOM GPS NAVIGATION MESSAGE QUESTION

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

https://preview.redd.it/42q1n14oe24e1.png?width=623&format=png&auto=webp&s=50e5b5043cc0f9904ec1c7ba4ce93ba853bdcc3a

I checked the "HelperGPSNAVEncode.m" file, and I see it saves it this way

https://preview.redd.it/24nbazv6f24e1.png?width=475&format=png&auto=webp&s=314d0cf2fd47f043f51bcb552c81ff5f3c05363d

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

https://preview.redd.it/wgl02lpvf24e1.png?width=661&format=png&auto=webp&s=26266d1983f9f87f7fd73e83065b01f62dab2718

Thank you

2 Comments
2024/11/30
16:32 UTC

0

can someone help me please this is till where i could go the below is the diagram i need to get but i can't so can someone help me with the matlab code please guys

1 Comment
2024/11/30
10:57 UTC

5

Thinkpad or Macbook Pro for MATLAB?

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.

12 Comments
2024/11/30
09:12 UTC

1

What's next after exporting the trained model in classification learner?

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

1 Comment
2024/11/30
03:33 UTC

1

PDE toolbox for Calculus

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:

https://youtu.be/Jt5R-Tm8cV8?si=cbhfAjP-paV7bh3R

0 Comments
2024/11/29
11:03 UTC

1

The line on the legend are not showing

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");

2 Comments
2024/11/29
10:17 UTC

0

control and simulation of a simple pick up and drop task for a robotic arm

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.

2 Comments
2024/11/29
08:08 UTC

1

CORDIC for division

this is CORDIC division

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?

4 Comments
2024/11/29
07:55 UTC

2

Problem with Gauss-Seidel method

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.

3 Comments
2024/11/28
21:18 UTC

0

For 50 W load, find Efficiency (𝜂) vs Duty Cycle (𝛿) relationship curves for Buck Converter Use duty cycle from 0.1 to 0.9 with 0.1 increment.

https://preview.redd.it/a8fihcgjcp3e1.png?width=1358&format=png&auto=webp&s=b040e9e9ee089e592968295942af1af352f8d026

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.

1 Comment
2024/11/28
20:30 UTC

0

Aiuto tesi in matlab

Ciao a tutti,

sono una studentessa magistrale all'università di Padova e cerco aiuto con una parte di codice in cui mi sono bloccata.

0 Comments
2024/11/28
16:02 UTC

9

How can I change AC source And use DC with inverter

6 Comments
2024/11/28
12:06 UTC

3

hi everyone, i have a problem with C2000 F28069m. it connect and deploy to board, but can't monitor it on simulink, have a noti like this. hope everyone can help me. Im so nervous about this

1 Comment
2024/11/28
06:19 UTC

0

ITS FOR DETECTING NOISE AND VIBRATION CHANNELS

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

3 Comments
2024/11/28
05:11 UTC

1

Simulink 2-phase fluid DCV

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

2 Comments
2024/11/28
04:48 UTC

0

Hello I need help with project which has a matlab code for analysis of channels in an audio file.....plz it's urgent

1 Comment
2024/11/28
03:33 UTC

3

Advice for storage of data in custom classes

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!

7 Comments
2024/11/27
23:13 UTC

0

EDG program

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…

0 Comments
2024/11/27
21:46 UTC

2

Help with diode open error in Simulink

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.

Error

Matlab Circuit

0 Comments
2024/11/27
21:26 UTC

Back To Top