/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

56,237 Subscribers

3 Comments
2024/03/17
15:27 UTC

2

Difference between Transport Delay and Delay

Hello everyone.
For a university project I need to run a simulink model given by the professor inside an optimization function such as fmincon.
Since the optimization is very long (colleagues of mine needed up to 10 hours), I wanted to optimize the simulink model.

I noticed that the transport delay block adds significant computational time and doesn't allow the model to be run in accelerator mode. I tried substituting it with a delay block with the same sample time as the time delay of the transport delay block.
This is the setup i used to compare their results:

https://preview.redd.it/r07d65vlbwoc1.png?width=711&format=png&auto=webp&s=6b55c023623bece633b88b5553a9d8c5c85f27bd

Running the model it can be noticed that after 0.004 s (it's the time delay i want), the delay changes its output while the transport delay keeps the same value as the initial condition as can be seen here:

https://preview.redd.it/c1y4tew3cwoc1.png?width=1121&format=png&auto=webp&s=ffe454d7986eeae6b48200dbd967356c8b1929ca

For the rest of the simulation the output from both blocks is identical.
However this little change enters in a control loop and the end the results of the optimization is completely different. Any idea about how I can improve this code efficiency without changing its results?

1 Comment
2024/03/17
13:29 UTC

1

Output size of the last layer does not match the response size help

Invalid training data. The output size [1 1 2] of the last layer does not match the response size [224 224 2].

net=vgg16();

dataFolder = fullfile('C:\Users\Maria\Desktop\Dom\Semantic Segmentation');

imageDir = fullfile(dataFolder,'trainingImagesResized'); labelDir = fullfile(dataFolder,'trainingLabelsResized');

imds = imageDatastore(imageDir); classes = ["Crack", "Crack_Free"]; labelIDs = [255 0];

pxds = pixelLabelDatastore(labelDir,classNames,labelIDs); cds = combine(imds,pxds);

pximds = pixelLabelImageDatastore(imds,pxds);

0 Comments
2024/03/17
13:28 UTC

0

Integral Calculation Accuracy Issue

I am trying to compute the integral of e^(-x^2) up to 25 decimal places. I’m not sure why, but this code can only calculate up to 16 decimal places accurately. To be honest, the code is mostly the work of ChatGPT, with minor edits from me.

I would appreciate any help on this :)))

syms x; f_sym = exp(-x^2);

a = 0; % lower limit b = 25; % upper limit

digits(25);

true_value_sym = int(f_sym, x, a, b, 'PrincipalValue', true);

true_value = double(vpa(true_value_sym, 25));

1 Comment
2024/03/17
10:07 UTC

1

System identification - transfer function estimation not working

I'm trying to fit a simple transfer function to some step change data.

The file StepTestingData.xlsx (uploaded here) contains three columns: time = [0, 1, 2, ..., 250], u = [...], y = [...].

The initial values of u and y are non-zero. u has value 64 for 0 <= t <= 6 and steps up by 2 to 66 for t >= 7. y has value about 30 for 0 <= t <= 16 and then moves due to the step change to a final value about 35.

I imported the data,

data = xlsread('StepTestingData.xlsx');
t = data(:,1);
u = data(:,2);
y = data(:,3);

then I opened up System Identification toolbox, imported it as a time domain signal (using start time = 0, sample time = 1), and the time domain plot shows the two signals as expected.

By inspection, a second-order transfer function with delay looked appropriate, so I clicked Estimate > Transfer function models and put # poles = 2, # zeros = 0, delay and unchecked the 'fixed' box, and clicked estimate. When it was finished I viewed the Model output graph and it did not fit at all. Here is a picture of the output.

Can anyone tell me why it's not working? Hopefully I've provided enough info, I appreciate it, thanks!

2 Comments
2024/03/17
00:06 UTC

2

Heart Animation

I'm trying to create a little animation of a heart using a formula.

I'm using the function animatedline correctly?

I appreciate any help or guidance.

https://reddit.com/link/1bgiz33/video/fnfc15cy3soc1/player

b = 100;
e = 2.718;

n = linspace(0,5,b);
x = linspace(-2*pi,2*pi,n);
y = x.^(2/3) + ((10-0.45*x.^2).^(1/2)) .* sin(n * pi* x);


h = animatedline(x,real(y));

for k = 1:b
	addpoints(h,x(k),y(k))
	axis([-2*pi,2*pi,-1.5,1.5])
	drawnow
end

0 Comments
2024/03/16
23:17 UTC

1

Any way to parallelise code without paying for the parallel computing toolbox?

Is there any method that I can use without having the paralel computing toolbox? I know parfor requires it, but maybe parfeval or some other method does not.

Also, I was also looking at doing code generation to speed up my code, but I don't know if I also need a paid plugin for that too. Is that something that I can do for free?

6 Comments
2024/03/16
20:41 UTC

1

HELP highlighting a datapoint in a plot of data specific to a state using a checkbox

Hi all,

I am very new to matlab, and am trying to add a component to an app I'm making. The app plots an x,y set of data from an excel spread sheet. each point is specific to a N.A. state. I want to add a check box for each state that when checked, will circle the data point asssociated to that state without getting rid of the rest of the points on my plot. I could also use a dropdown if its easier.

Thanks for your time

1 Comment
2024/03/16
18:01 UTC

1

Help with 'Area Figure'

Hello, I am currently doing the standard precipitation index and need a code for the figure as given. Can anyone who can help me with the code or suggest a chart type for this? I tried area but it's just not working.

This is the data type:

Years: 1901 to 2020

Hello, I am currently doing the standard precipitation index and need a code for the figure as given. Can anyone who can help me with the code or suggest a chart type for this? I tried area but it's just not working.

0 Comments
2024/03/16
15:42 UTC

1

Performing the Transportation Simplex Algorithm in MATLAB help

For my undergrad dissertation I am attempting to solve transportation problems in matlab. I've got a feasible solution from transportation methods (NWCM, minimum cost method, Vogels method & Russels method) and I am now attempting to solve the BFS matrix further by the transportation simplex algorithm. My code can only identify loops on certain small matrices, and I need it to work for 14x15 matrices.

I think the problem occurs somewhere here

loop= length(BVind);
ind=[];
disp('BVind:');
disp(BVind);
while loop >0
ind(length(ind)+1,:)= [costBVs(BVind(loop,1),BVind(loop,2))];
loop=loop-1;
end
minValue = min(ind(ind > 0));
val= length(ind);
while val >0
ind(val,:)= ind(val)+minValue;
val= val-1;
if val >0
ind(val,:)= ind(val)-minValue;
val=val-1;
else
break
end
end
ind=flip(ind);
loop= length(BVind);
while loop>0
costBVs(BVind(loop,1),BVind(loop,2))= ind(loop);
loop=loop-1;
end

I have attached the part of the function in pictures.

Any assistance will be greatly appreciated :)

identifys entering variable and attempts to find loops

https://preview.redd.it/tjcayqkhkpoc1.png?width=640&format=png&auto=webp&s=9a62302a529baa144d830658f9180fedc4028e45

0 Comments
2024/03/16
14:33 UTC

0

Installed matlab but...

So last night I downloaded matlab and installed it but it seems it's missing some files for some reason, as soon as the installation finished it didn't create a shortcut on desktop or the start menu, so I figured that the "matlab.exe" file is missing and so I was right, I tried reinstalling but it didn't change anything, I can't afford to download the whole thing again so I was hoping if someone can send me the file alone which is about 200kb only, here's the path for the file
C:\program Files\MATLAB\R2023a\bin\Win64

5 Comments
2024/03/16
11:27 UTC

1

Graphing Multiple Lines in a for loop help

Hey, so to preface this is a snippet of a larger code, but since that larger context is mostly irrelevant, I've truncated it down to this to focus on this specific coding problem.

To summarize, I'm trying to graph multiple lines on a singular figure in a for loop, and my code looks like below:

T = [1,2,3;2,4,6;3,6,9];
A = 2*T;
for i=1:3
hold on
figure(i)
plot(1:3,T(i,:)); plot(1:3,A(i,:));
hold off
end

The code functions normally for the first figure and graphs the two lines like so:

https://preview.redd.it/k9row1sq6noc1.png?width=203&format=png&auto=webp&s=92b5e7f3551ffbf729f5768155709a195408df05

But for both figure 2 and figure 3 it only ever graphs the first line.

https://preview.redd.it/k53u6mpw6noc1.png?width=262&format=png&auto=webp&s=bd4b4940296616faeb373ac814a0381bc565a2bb

https://preview.redd.it/wb0oed407noc1.png?width=278&format=png&auto=webp&s=bbfc0379e2c243a997ee839d4f500b04e372750e

What seems to be the problem that is causing this and how can I fix it? Thanks.

2 Comments
2024/03/16
06:43 UTC

1

New to MATLAB/Simulink need help in performing load flow analysis for the model given below

I've tried searching for videos online for help but they seem to use models that are far simpler and don't really help very much. I've tried adding load flow buses but Simulink keeps throwing an error when I try performing load flow using powergui. I've tried running it without adding any load flow buses and it works but I'm getting some weird values.

https://preview.redd.it/rk9sxt261noc1.png?width=1356&format=png&auto=webp&s=093057b9ce449e039689ae234d7118b5964cbd5a

Link to the model on Mathworks: https://in.mathworks.com/help/sps/ug/24-hour-simulation-of-a-vehicle-to-grid-v2g-system.html#d126e68772

0 Comments
2024/03/16
06:09 UTC

3

Matlab translation from Python

Hi, I'm stuck on this for quite sometime and have no clue what's wrong but does anyone know the equivalent of

sum(function(l,k) for l in range(1,n+1) for k in range(1,n+1)) in Python for Matlab?

What I wrote in Matlab:

sum(arrayfun(@(l, k) function(l, k), 1:n, 1:n))

The numerical answer differs by ~0.02. The function itself gives the same numbers for both Matlab and Python, so it's not the function that has a bug.

I am using format long in Matlab to get more decimals so it's not rounding sooner than Python.

Anyone has any clue what's going on?

7 Comments
2024/03/16
00:37 UTC

0

Syntax Highlighting (small rant)

I don't understand. Matlab is widely used. Why on earth can we not get an updated IDE with basic features like syntax highlighting. There are numerous free editors with these basic features. Would it really be that hard for Mathworks to add some features?

14 Comments
2024/03/15
16:21 UTC

3

Gauss-Seidel method code help

Hello, I have this task but my code is clearly not giving me the wanted result. I checked it with the code my professor gave, everything works fine, but with mine it does not even converge.

Task:

Compute the solution of the linear algebraic equations system [A]{x}={b}:

  1. Make calculations by hand using the Native Gauss elimination method
  2. Using the Gauss-Seidel iterative method for the terminating tolerance e=10*^(-3)* and the initial approximation x0 = [0; 0; 0]
  3. Check results by Matlab „\“

My code:

clc
clear

% Given equations:
% 6a - b = 8
% -b + 6c = 8
% -a + 6b - c = -14

% Coefficients matrix A
A = [6, -1, 0; 0, -1, 6; -1, 6, -1];

% Constants vector B
B = [8; 8; -14];

% Initial approximation
x0 = [0; 0; 0];

% Tolerance
e = 1e-3;

% Gauss-Seidel Iterative Method
x = x0;
iter = 0;
x_history = []; % To store history of x values for plotting

while true
    iter = iter + 1;
    x_old = x;
    
    % Update x1 (a)
    x(1) = (B(1) - A(1,2)*x(2) - A(1,3)*x(3)) / A(1,1);
    
    % Update x2 (b)
    x(2) = (B(2) - A(2,1)*x(1) - A(2,3)*x(3)) / A(2,2);
    
    % Update x3 (c)
    x(3) = (B(3) - A(3,1)*x(1) - A(3,2)*x(2)) / A(3,3);
    
    % Store current x values for plotting
    x_history = [x_history, x];
    
    % Check for convergence
    if max(abs(x - x_old)) < e
        break;
    end
    
    % Terminate if the maximum number of iterations is reached
    if iter > 100
        disp('Maximum number of iterations reached without convergence.');
        break;
    end
end

disp(['Solution converged in ', num2str(iter), ' iterations.']);
disp(['a = ', num2str(x(1))]);
disp(['b = ', num2str(x(2))]);
disp(['c = ', num2str(x(3))]);

% Plotting
figure;
subplot(3,1,1);
plot(1:iter, x_history(1,:), '-o');
title('Convergence of a (x1)');
xlabel('Iteration');
ylabel('Value');

subplot(3,1,2);
plot(1:iter, x_history(2,:), '-o');
title('Convergence of b (x2)');
xlabel('Iteration');
ylabel('Value');

subplot(3,1,3);
plot(1:iter, x_history(3,:), '-o');
title('Convergence of c (x3)');
xlabel('Iteration');
ylabel('Value');

% -----------------------------
C=A\B

RESULTS:

Maximum number of iterations reached without convergence. Solution converged in 101 iterations.

a = -1.109367434363749e+154

b = -2.394383283640223e+156

c = -1.43552060274977e+157

ACTUAL ANSWER:

C=

1.0000

-2.0000

1.0000

10 Comments
2024/03/15
15:46 UTC

3

fixed vs float point algo performance comparision

I have developed an algorithm for my error controller, which is written in pure C, floating point.

Now I'm trying to port it to RTL, hence using a fixed point format for a word-length of 16 bits.

What's the the standard way of comparing performance (quant noise, phase error, precision trade-off ) in Matalb/Simulink.

1 Comment
2024/03/15
13:50 UTC

2

Reassigning arrays — will it creates a new array instead?

Suppose that I have this array:

dt = [3 2 1 0]

Then I decided to add a new element at the first index. This is the way I know:

dt = [4 dt]

What I want to know is if this operation, instead of adding a new element to the original array, copies it and ‘cuts’ it away from the variable it was assigned to, so he original won't be associated with dt anymore, but it still exists in the memory. So it looks like this:

Before  :
dt ---> [3 2 1 0]

After:
dt -//  [3 2 1 0]
dt ---> [4 3 2 1 0]

Does it actually happen like that?

3 Comments
2024/03/15
10:49 UTC

2

How to generate a custom wave using signal generator

https://preview.redd.it/xl2vc7yuwfoc1.jpg?width=1600&format=pjpg&auto=webp&s=2f31792dc38b78b9821aa9e58ac3320e3756aca1

I want this wave as an input to a matlab function in simulink. I have tried using signal generator but not able to get this specific wave

1 Comment
2024/03/15
06:15 UTC

0

I can’t open MATLAB

I tried to open matlab to do some homework and I got a pop up in its place saying that there is an issue, specifically error 5021, I went to the help tab and followed the guide to fix this but when I tried to open it again now it just says error 5022, tried to fix it with the guide, didn’t work, tried to completely erase matlab and redownload it, it still doesn’t work, am I doing something wrong, has this happened to any of you? anyone knows how to fix this?

1 Comment
2024/03/15
04:30 UTC

1

Need help to run my matlab model but the model is from 2016b.

3 Comments
2024/03/15
04:14 UTC

1

Having trouble combining data from multiple figures into one

I have a long list of figures consisting of two different lines in the xy plane. I've combined figures like these in the past into one single figure, but the method I used doesn't seem to be working here. Is there a simple way in which I could combine all of these figures into one graph consisting of both lines?

4 Comments
2024/03/14
22:05 UTC

1

Lastools and Matlab

Hello to everyone, I have an issue anyone could help me please? I want to read and classify laz data in Matlab using a extension of lastools in Matlab and I don’t know how to incorporate lastools to my code please anyone can help me in this? I want to reclassify my pointclouds using algorithms and I don’t know it’s better reclassify and export in new output path or is better rewrite the laz data #lidar #lastools

0 Comments
2024/03/14
13:06 UTC

1

Cloud computing

I need info about using matlab via cloud computing. I'm working on a script with a large amount of data that my pc can't process so i think that using cloud computing can be a solution (obviously other options are well accepted).

2 Comments
2024/03/14
07:21 UTC

2

How do I verify that this audio signal has an SNR of 0 dB?

I am looking to verify the claims in this official matlab sample code here

https://www.mathworks.com/help/deeplearning/ug/denoise-speech-using-deep-learning-networks.html

[cleanAudio,fs] = audioread("SpeechDFT-16-8-mono-5secs.wav");
noise = audioread("WashingMachine-16-8-mono-1000secs.mp3"); % Extract a noise segment from a random location in the noise file
ind = randi(numel(noise) - numel(cleanAudio) + 1,1,1);
noiseSegment = noise(ind:ind + numel(cleanAudio) - 1); 
speechPower = sum(cleanAudio.2); 
noisePower = sum(noiseSegment.2); 
noisyAudio = cleanAudio + sqrt(speechPower/noisePower)*noiseSegment;   % ---> (1)

The gist is that they take an equal sized sample of both pure speech and pure noise file, then add them together multiplying the noise sample with a certain value that makes the combined signal have an SNR of 0 dB. I have my own implementation of this method where I use two wav files of each length, one with pure speech and one with pure noise. Then I use (1) above to mix them together to get a noisy wav file.

How do I verify that SNR is actually 0?

The method I normally use is something like this:

residual_noise = clean_speech - noisy_speech;   % getting the difference between desired signal (clean_speech) and actual signal (noisy_speech)
snr_after = sum( clean_speech .^ 2 ) / sum( residual_noise .^ 2 ); 
snr_after_db = 10 * log10( snr_after )

On paper, if I use this method on the `noisyAudio` signal above, I get a exact snr of 1 ( = 0 dB) because during division operations the numerators and denominators cleanly cancel each other out. However, if I make this program in matlab, replace `clean_speech` with the audio sample from my pure speech wave file and `noisy_speech` with the `noisyAudio` value calculated above, I do not get 0 dB SNR.

Is there something in the original matlab code that I am not getting, or is my method to calculate snr not correct here?

4 Comments
2024/03/14
03:56 UTC

1

Adding Sound Clips

Hello, I have recorded some sound files from my phone and converted them into wav files in order to use them in my matlab code, however, whenever I try add these sound clips in my code I get stuck. I get error such as invalid variable or not defined, even worse get no error and it just does not play.

I have tried the examples in the official matlab website however it seems that my Mac is not even playing handel?! So I was also wondering if this is a problem with my code or Macbook.

I have also tried creating .mat files but mostly got stuck again because honestly it confused me.

Thank you in advance for any help!!

1 Comment
2024/03/13
22:59 UTC

1

Struggling to graph simple functions

Hello, for my second semester of uni we are required to learn some basics of MATLAB and utilize it in calculus and other applied mathematics.

I have been trying for the past hours to understand how plot, fplot and plotting functions in general work. I need to plot these 2 functions:

y1 = (2*(x.^2)+x)./(x+3).^4;
y2 = (3*x-x.^3)./(x-5).^4;

I have been struggling hard to understand how to have both functions in the same plot, it keeps either not working at all, looking weird, or I can only get one function to show up. I have looked at the guide my school gives me, online resources and other stuff and I can not for my life figure this simple thing out. Heres my code if anyone interested, its a mix of things I found in guides that I was praying would work for me

x = linspace(-20, 20);
x(x == -3) = []; % Exclude x = -3
y1 = (2*(x.^2)+x)./(x+3).^4;
y2 = (3*x-x.^3)./(x-5).^4;
fplot(y1);
hold on
fplot(y2);
hold off
axis on;
grid on;
ylim([-10, 10]) %

6 Comments
2024/03/13
22:40 UTC

Back To Top