/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
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:
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:
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?
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);
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));
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!
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
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?
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
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:
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
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
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:
But for both figure 2 and figure 3 it only ever graphs the first line.
What seems to be the problem that is causing this and how can I fix it? Thanks.
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.
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
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?
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?
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}:
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
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.
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?
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
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?
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?
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
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).
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?
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!!
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]) %