/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

64,761 Subscribers

1

What is this block?

Hi, can someone help me identify the middle block.

https://preview.redd.it/7kqgcao92sge1.png?width=675&format=png&auto=webp&s=b91f1424562ef23246eab7dd83b860c31c65e04f

It looks like a Sign Block but I'm not sure. Thanks.

0 Comments
2025/02/02
19:30 UTC

1

Plotting netCDF File

I need to plot the temperature of a netCDF file but I’m missing the latitude and longitude variables to do so. It’s there any other way to plot this ?

0 Comments
2025/02/02
19:23 UTC

1

Please help! (Spm12 issue)

I’m a new to matlab and coding in general. I recently downloaded matlab to my computer in addition to SPM12.

For some reason my SPM interface doesn’t show the two options “Specify 1st-level” or “Specify 2nd -level”. These options are all displayed on every video and manual I’ve come across.

I’m not sure why they aren’t available to me. If anyone could help me understand or knows an alternative solution, please let me know!!

4 Comments
2025/02/02
19:09 UTC

12

Please explain why 2 models with the same parameters but different voltage out?

3 Comments
2025/02/02
17:35 UTC

2

Struggling with matlab

Hello! I’m going to put it as simply as possible I’m so beyond lost on how to use matlab / code in general… any advice? I’ve been having friends help me or using online resources to break down what and how I’m supposed to be doing things but I want to be more independent. I was told that there wasn’t going to be coding involved in this class I’m taking so I came in not knowing anything at all... I’ve wanted to reach out to my TA to help me but I don’t feel comfortable . If anyone has any advice or willing to help I would be so so sooooo grateful

5 Comments
2025/02/02
12:58 UTC

1

Engineering Development Group (EDG)

I have to submit the video resume for the role of an EDG intern. I also have to complete the coding round before that.

All of this I have to complete by Feb 6. Any tips are welcome, esp on resume content and questions. Thank you

0 Comments
2025/02/02
05:35 UTC

1

Problem of simulating s parameters of branch line coupler

I am stimulating the branch line coupler in the first ppt you have given, and I found that while it could stimulate S11 and S31 in different wavelength, I found it could not stimulate S21 and S41 correctly, instead they overlap with S31 and S21 respectively.This is my code:

Z=50;

Z1=Z/sqrt(2);

omega=0:0.01:2;

syms S11 S21 S31 S41;

for i=1:1:201

resOdd=1;

Odd1=[1,0;-1i/Z,1];

Odd2=[cos(pi/2/omega(i)),1i*Z1*sin(pi/2/omega(i));1i*sin(pi/2/omega(i))/Z1,cos(pi/2/omega(i))];

resOdd=resOdd*Odd1*Odd2*Odd1;

AOdd=resOdd(1,1);BOdd=resOdd(1,2);COdd=resOdd(2,1);DOdd=resOdd(2,2);

S11Odd=(-DOdd+AOdd-Z*COdd+BOdd/Z)/(DOdd+AOdd+Z*COdd+BOdd/Z);S21Odd=2*Z/(Z*DOdd+Z*AOdd+Z^2*COdd+BOdd);

resEven=1;Even1=[1,0;1i/Z,1];

Even2=[cos(pi/2/omega(i)),1i*Z1*sin(pi/2/omega(i));1i*sin(pi/2/omega(i))/Z1,cos(pi/2/omega(i))];

resEven=resEven*Even1*Even2*Even1;

AEven=resEven(1,1);BEven=resEven(1,2);CEven=resEven(2,1);DEven=resEven(2,2);

S11Even=(-DEven+AEven-Z*CEven+BEven/Z)/(DEven+AEven+Z*CEven+BEven/Z);S21Even=2*Z/(Z*DEven+Z*AEven+Z^2*CEven+BEven);

S11a=abs((S11Even+S11Odd)/2);

S21a=abs((S21Even+S21Odd)/2);

S31a=abs((S21Even-S21Odd)/2);

S41a=abs((S11Even-S11Odd)/2);

S11(i)=20*log10(S11a);S21(i)=20*log10(S21a);S31(i)=20*log10(S31a);S41(i)=20*log10(S41a);

end

plot(omega,S11)

hold on

plot(omega,S21)

hold on

plot(omega,S31)

hold on

plot(omega,S41)

hold off

P1 is my stimulation result:

https://preview.redd.it/g04662ewnnge1.jpg?width=840&format=pjpg&auto=webp&s=22403c4e793c96799d5b260c4b878e51d8aa6639

and P2&P3 is the stimulation result from other researches of branch line coupler:

https://preview.redd.it/3nl8s4oxnnge1.png?width=936&format=png&auto=webp&s=cd9e1d2324602e95a3ef66f9ed50e66b905390d5

https://preview.redd.it/5mdeuxjynnge1.png?width=512&format=png&auto=webp&s=bcb60670b28f027250bdcec65fe3d6f3bede8319

I have checked both my code and the scale conversion between frequency and wavelength, from which I still could not understand how the results are not matched.

0 Comments
2025/02/02
04:45 UTC

0

How to solve this differential equation:

1 Comment
2025/02/02
03:32 UTC

0

What is and how do you use RefCoeff?

https://preview.redd.it/hpg1qbokelge1.png?width=202&format=png&auto=webp&s=cc6c94f8c555dc080cb801d1db80d0ea9541c714

Does anyone know what this function (RefCoeff) does or what parameters it takes? I did look it up but it didn't show up anywhere. I know it has something to do with the reflection coefficient. What are the parameters though?

1 Comment
2025/02/01
21:07 UTC

3

Simulating a Conveyer Belt in Simulink

I'm trying to simulate an Industrial Control unit in Simulink, for a larger project. So, for starters I have tried to create a Conveyer belt (on the right) which is connected to two rollers. There is also a DC motor connected to a 1:1 Gear which connects to a rotational motion sensor, which connects to an Inertia Block.

Now, I'm trying to connect the inertia block to the rollers to make the full circuit and try to run this thing, but I can't.

I don't know if the configuration has mistakes, or am I missing something. If anyone knows anything about it, please leave a comment.

2 Comments
2025/02/01
19:49 UTC

2

Time table to MF4 with mera data.

Hello guys!

I'm working on a project which needs to convert time table to MF4. Doing this is the easy part.

I have lots of signals in the time table need to add units. Not sure on how to proceed, I'd appreciate any leads possible.

Thanks.

4 Comments
2025/02/01
03:08 UTC

1

Can simulink be used as a game engine ?

I was at a supersonic drone club yesterday and the leader was showing the simulation of the drone through simulink and was controlling it using a joystick and then it hit me. Even though it’s not specifically made to be one could simulink be used as a game engine like unity ?

7 Comments
2025/02/01
01:05 UTC

1

Needed row not importing

https://preview.redd.it/j88daou3uege1.png?width=1347&format=png&auto=webp&s=6613a668a795b42f3102d3a07de2e8457694a922

So, I am trying to import this data from excel into matlab, but it is not letting me import the titles for the data. How do I make it import that row? If I turn off the change things to NaN it just makes it where it can't import.

Thank you!

2 Comments
2025/01/31
23:04 UTC

2

Please help. Scope not opening in simulink

I was working on a project and accidentally clicked on something without noticing and now none of the scopes wanna open no matter how how many times I click on them. I checked all background windows and there’s nothing there. I even tried getting a new scope from the library but even that doesn’t wanna open. Only time scope works. Can someone please help me get it working again?

Ps. I’m a noob to matlab so sorry if this is a common issue. Also I’m using the 2015 version

3 Comments
2025/01/31
15:14 UTC

1

Wireless Channel Simulation

1 Comment
2025/01/31
15:05 UTC

2

3d rotator for any set of points (not just pringles)

1 Comment
2025/01/31
00:55 UTC

1

what is this simulink block

2 Comments
2025/01/31
00:55 UTC

1

Plot a figure from multiple .fig files

I have run multiple simulations of a system and in each run I changed one parameter. I saved the .fig files of a scope I am interested in but the scope plots 2 figures separated by the layout function (so there is one on top and one on the bottom part when you click/view the scope). How can I plot only the top figure (1st input in the scope) from the various .fig files that I saved? I want to highlight the difference when I change a specific parameter (increase and decrease) and repeat for each parameter that I changed.

Thank you a lot in advance!

2 Comments
2025/01/30
16:46 UTC

0

Solve a pde equation with finite differences for Simulink

Hello , I want to transform this code that solves a pde equation with the ode solver into finite diferences, because I want to take the code as a matlab function block in simulink so it stands no ode solver(since it is an iterator take much time every time step so never ends simulation ) thats why i want to take it into finite differences .The equations are the following

https://preview.redd.it/35eo0u8pt4ge1.png?width=556&format=png&auto=webp&s=5c27f5ffef541cf19ec765b652a6df4327be0d3a

The inital code is the following with ode solver:

L = 20 ; % Longitud del lecho (m)

eps = 0.4; % Porosidad

u = 0.2; % Velocidad superficial del fluido (m/s)

k_f = 0.02; % Constante de transferencia de masa (1/s)

c0 = 0;

Kf = 4; % Constante de Freundlich

rhop = 1520;

n = 2; % Exponente de Freundlich

% Concentración inicial del fluido (kg/m³)

q0 = 4.320; % Concentración inicial en el sólido (kg/m³)

% Densidad del adsorbente (kg/m³)

tf = 10; % Tiempo final de simulación (horas)

Nt = 100;

t = linspace(0, tf*3600, Nt);

Nz = 100;

z = linspace(0, L,Nz);

dz = z(2) - z(1);

% Initial conditions

ICA = max(ones(1, Nz) * c0, 1e-12); % Evitar valores negativos o cero

ICB = ones(1, Nz) * q0;

IC = [ICA ICB];

options = odeset('RelTol', 1e-6, 'AbsTol', 1e-8, 'InitialStep', 1e-4, 'MaxStep', 100);

[t, y] = ode15s(@fun_pde, t, IC, options, Nz, eps, n, Kf, k_f, u, rhop, dz);

% Define value

cc = y(:, 1:Nz);

qq = y(:, Nz+1:end);

% Recalculate new limit conditions

cc(:, 1) = 0;

cc(:, end) = cc(:, end-1);

% Plotting

cp = cc(:, end) ./ c0;

qp = qq(:, :) ./ q0;

%q_promedio = mean(qq, 2); % Promedio de q en el lecho para cada instante de tiempo

%conversion = 1 - (q_promedio / q0); % Conversión normalizada

figure;

subplot(2, 1, 1);

time = t / 3600; % Convertir a horas

plot(time, 1- qp, 'b', 'LineWidth', 1.5);

xlabel('Tiempo (horas)');

ylabel('Conversion');

title('Curva de conversión durante la desorción');

grid on;

subplot(2, 1, 2);

plot(t / 3600, (cc(:,:)), 'LineWidth', 1.5);

xlabel('Tiempo (horas)');

ylabel('Soluciòn kg/m3');

title('Curva de carga de la solucion durante la desorciòn');

grid on;

% PDE function

function dydt = fun_pde(~, y, Nz, eps, n, Kf, k_f, u, rhop, dz)

dcdt = zeros(Nz, 1);

dqdt = zeros(Nz, 1);

c = y(1:Nz);

q = y(Nz+1:2*Nz);

% Boundary conditions

c(1) = max(c(1), 0); % Asegurar que c(1) sea no negativo

c(end) = c(end-1); % Asegurar que c(1) sea no negativo

% Interior nodes

qstar = zeros(Nz, 1);

dcdz = zeros(Nz, 1);

for i = 2:Nz-1

qstar(i) = Kf .* max(c(i), 1e-12).^(1/n); % Evitar problemas numéricos

dqdt(i) = k_f .* (qstar(i) - q(i));

% if i < Nz

dcdz(i) = (c(i+1) - c(i-1)) / (2 * dz);

%else

% dcdz(i) = (c(i) - c(i-1)) / dz;

%end

dcdt(i) = -u * dcdz(i) - rhop * ((1 - eps) / eps) .* dqdt(i);

end

dydt = [dcdt; dqdt];

end

https://preview.redd.it/703vhfty35ge1.png?width=583&format=png&auto=webp&s=8806a5e61114422577d75dfda439518d0ae29f9c

next is a try to solve with finite diferences but get someting different:

L = 20 ; % Longitud del lecho (m)

eps = 0.4; % Porosidad

u = 0.2; % Velocidad superficial del fluido (m/s)

k_f = 0.02; % Constante de transferencia de masa (1/s)

c0 = 0; % Concentración inicial del fluido (kg/m³)

Kf = 4; % Constante de Freundlich

rhop = 1520; % Densidad del adsorbente (kg/m³)

n = 2; % Exponente de Freundlich

q0 = 4.320; % Concentración inicial en el sólido (kg/m³)

tf = 10; % Tiempo final de simulación (horas)

Nz = 100; % Número de nodos espaciales

% Discretización espacial y temporal

z = linspace(0, L, Nz);

t = linspace(0, tf*3600, Nt);

dz = z(2) - z(1);

dt = t(2) - t(1); % Paso temporal

% Condiciones iniciales

c = ones(Nt, Nz) * c0; % Concentración en el fluido

q = ones(Nt, Nz) * q0; % Concentración en el sólido

% Iteración en el tiempo (Diferencias Finitas Explícitas)

for ti = 1:Nt-1

for zi = 2:Nz-1

% Isoterma de Freundlich

qstar = Kf * max(c(ti, zi), 1e-12)^(1/n);

% Transferencia de masa (Desorción)

dqdt = k_f * (qstar - q(ti, zi));

% Gradiente espacial de concentración (Diferencias centradas)

dcdz = (c(ti, zi+1) - c(ti, zi-1)) / (2 * dz);

% Ecuación de balance de masa en el fluido

dcdt = -u * dcdz - rhop * ((1 - eps) / eps) * dqdt;

% Actualizar valores asegurando que sean positivos

c(ti+1, zi) = max(c(ti, zi) + dcdt * dt, 0);

q(ti+1, zi) = max(q(ti, zi) + dqdt * dt, 0);

end

end

% Condiciones de frontera

c(:, 1) = c0; % Entrada con concentración baja

c(:, Nz) = c(:, Nz-1); % Gradiente nulo en la salida

% Cálculo de la conversión normalizada

qp = q(:, :) ./ q0;

% Graficar resultados

figure;

subplot(2, 1, 1);

plot(t / 3600, 1-qp, 'b', 'LineWidth', 1.5);

xlabel('Tiempo (horas)');

ylabel('Conversion');

title('Curva de conversión durante la desorción');

grid on;

subplot(2, 1, 2);

c_salida = c(:, :); % Concentración en la salida del lecho

plot(t / 3600, c_salida, 'r', 'LineWidth', 1.5);

xlabel('Tiempo (horas)');

ylabel('Soluciòn kg/m3');

title('Curva de carga de la solucion durante la desorciòn');

grid on;

https://preview.redd.it/hkdiayil55ge1.png?width=583&format=png&auto=webp&s=ecfe903d8f0821aa102d5a0ccc25345cfaca9c19

I dont know where is wrong .Thanks in advance

1 Comment
2025/01/30
14:30 UTC

96

Rotating pringle code

clear, clc, close all

t = [-3.14:0.025:3.14];

x = [sin(pi*t)];

y = [1.5cos(pit)];

i = 0.9;

a = 0.05;

while i > 0

t = [-3.14:a:3.14];

x = [x,isin(pit)];

y = [y,1.5icos(pi*t)];

i = i - 0.1;

a = (i^-1)*.05;

end

z = 0.5*((x.^2) - (0.5*(y.^2)));

s = 0;

d = 5;

f = 5;

while s < 10000

yrot = (ycos(pi/270)) + (zsin(pi/270));

zrot = -(ysin(pi/270)) + (zcos(pi/270));

y = yrot;

z = zrot;

xrot = (xcos(pi/180)) - (ysin(pi/180));

yrot = (xsin(pi/180)) + (ycos(pi/180));

x = xrot;

y = yrot;

xproj = x.*(f./(y+d));

zproj = z.*(f./(y+d));

plot(xproj,zproj,'.')

xlim([-2,2])

ylim([-1.6,1.6])

title('haha pringle go brrr')

s = s + 1;

drawnow

end

11 Comments
2025/01/30
04:07 UTC

2

fat sine wave?

Is there a way to create a fatter version of a sine wave? Close to a square wave but still rounded on the edges.

Here's the unfattened sine wave I'm using. . .

t = linspace(0, 1, 8400); % Time vector from 0 to 1 second

yy1 = sin(2*pi*8*t); % Sine wave function

11 Comments
2025/01/30
02:36 UTC

4

GPU Recommendation for MATLAB Programming

Hi everyone! Which GPU Brand do you recommend for me? I'll be working on deep learning with Images in MATLAB, and currently, my GPU is NVIDIA GeForce GTX 1050 TI. I'm considering upgrading to Palit NVIDIA GeForce RTX 3060 DUAL 12GB GDDR6 192-bit DP+HDMI since it has 12GB of VRAM and a 192-bit interface.

Please let me know what is best for price and performance. I have included some details about my workstation. Thank you.

Processor: AMD Ryzen 5 3600 6-Core Processor 3.60 GHz
RAM: 32 GB Corsair
System Type: 64-bit operating system, x64-based processor
Windows: Microsoft Windows|
GPU: NVIDIA GeForce GTX 1050 TI
OS: Windows 11
SDD: Kingston 500 GB (NVMe)
HDD 1: Toshiba 1 TB (S-ATA Gen 3, 6 Gbps)
HDD 2: Seagate 2 TB (S-ATA Gen 3, 6 Gbps)

4 Comments
2025/01/30
00:53 UTC

3,183

Made this for a class. Professor was impressed.

42 Comments
2025/01/30
00:36 UTC

1

Simscape Circuit is giving me an error.

Hello,

I am very new to Matlab and my instructor was not sure how to fix my problem. I'm trying to simulate an AC circuit that contains a current dependent voltage source. I'm using a current meter to get the value of the current in question and then I'm using a gain block to multiply that current by 39. The dependent source should have a voltage equal to 39*I_x , where I_x is the current. Normally this works fine, but this time, having the gain be higher than 30 causes a problem. I'm not sure precisely what the error code is trying to tell me other than the fact that it has highlight my current meter as a problem.

I'd really appreciate it if someone more knowledgeable than me could look at the screenshot and file.

Link to Dropbox for the .slx file (Hopefully this is okay) - Link

Thank you

EDIT - It may be Simulink and not Simscape. Apologies if I'm wrong.

0 Comments
2025/01/29
23:40 UTC

3

Desorption reactor design in simulink

Hello, I want to model a desorption reactor with a fixed bed containing gold-laden carbon, through which a desorbing solution passes, which extracts extra gold. I am trying to solve it using a PDE system in which I create multiple nodes, assimilating it as if it were solved using the finite difference method. Using a forward difference for the initial node, a central difference for the intermediate nodes, and a backward difference for the final node. These are relative to a distance differential.The equations are as follows.

https://preview.redd.it/qpo0ih3g80ge1.png?width=556&format=png&auto=webp&s=02f64c1a043537866034d567b5a7c9cb53b96391

So i tried finite differences for dc/dz with forward difference for eactor entry , central along the reactor , and backward in the exit, and dc/dt and dq/dt use integrator blocks, I consider Co= 0 kg/m3 solution and q0=4.320 kg/m3 carbon. Just considering 5 nodes , shall be more but first i want to make the first five work fine .

https://preview.redd.it/cy37eemg80ge1.png?width=1197&format=png&auto=webp&s=745e2fc00a9de72f3f405e7537a7eff6993594a6

And each node consist on the following layout , where can be seen a time integral block term for q(carbon loading) and c(solution loading , it shows also a length step and inputs from the forwarded and current node soluction concentration(in the case of the first node)

https://preview.redd.it/cda8i6ch80ge1.png?width=1233&format=png&auto=webp&s=0887350dca2186570fecbcee5547c9d95917ff1f

My problem is that I am getting the same values on each node, which I don't know if it is right the layout approach, since they should be different with relation to time and besides when i increase or decrease the input stream speed , the values in carbon and solution loading not change at all. thanks in advance

File is attached in the link : https://riveril123.quickconnect.to/d/s/11wyBkc59ZycO0kl7OwWITAm221uWy5e/hgq22s1F0Ty03_NsErAwiuc3kyxewhUM-urqAt1qkAww

0 Comments
2025/01/29
21:55 UTC

1

MATLAB SATCOM GPS NAVIGATION MESSAGES GENERATION

Hello,

I am currently studying the gps standard and the user position calculation I would like to know if there is a way to generate a gpsL1 navigation message that contains auto sets all the different values to correspond to a specific satellite in a certain time and date In the website https://in-the-sky.org/satmap_worldmap.php?gps=1 it is actually possible to check for satellites' positions and parameters at some given date What i am needing is a way to input into the MATLAB navigation message generator, time date and number of satellite, so it automatically sets all parameters which are contained inside the navigation message, such as clockdrift, seminajor, perigee, etc, so i can then extract those values and validate my position calculations

To clarify, I've already created custom lnav messages, but with known navigation message parameters

0 Comments
2025/01/29
16:17 UTC

Back To Top