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

- Mathworks (student tutorial)
- MIT OCW (online shortcourse)
- Northwestern Tutorial (for engineers)
- Project Euler (mini challenges)
- Matlab Cody (mini challenges)

- Matlab Central
- Matlab Answers
- Matlab File Exchange
- Undocumented MATLAB
- Loren's Art of MATLAB Blog
- Tpn86's cheat sheet

Try saturnapi to share and run MATLAB code in a web browser!

If you want flair simply Message the mods

/r/matlab

1

I'm using matlab to process a number of datasets. Some of these datasets are worth processing (good) and some not (bad). Given the long processing time per dataset, I would like to eliminate/not pick bad datasets before processing them. There's no straightforward way for me to do this in matlab (set a criterion etc).

I'm a total AI/ML noob but I was wondering if there's a way to create a model that I can feed handpicked "bad" datasets that then goes on to identify the same in a much larger set. Is this possible?

Thanks!

0 Comments

2023/09/30

22:42 UTC

22:42 UTC

3

Hello guy,

I am a newbie in Matlab, recently I got a task that used some data from the workspace to plot in app designer but it had too much value to hand on manually, so I used a loop, which can describe in this picture below. I dont understand how i can get a value from wspace to appdesigner.

I hope someone can help me solve this problem, thank you very much!

3 Comments

2023/09/30

13:00 UTC

13:00 UTC

0

Hello guy,

I am a newbie in Matlab, recently I got a task that used some data from the workspace to plot in app designer but it had too much value to hand on manually, so I used a loop, which can describe in this picture below. I dont understand how i can get a value from wspace to appdesigner.

I hope someone can help me solve this problem, thank you very much!

0 Comments

2023/09/30

13:00 UTC

13:00 UTC

1

I made Simulink simulation of an Differential equation and a livrscript to User the Model. Everythink worden fine at Homepage but when I try to User the same Script an Model within MATLAB Online I get a strange error: " '@ab_c_ mod[' is Not a valid Model name because it is Not a valid MATLAB function name "the strange Thing is the is no [ or @ in my Script nor in the name of the model. I tried to load the Model with " modelfile = 'ab_c_mod'; c"

8 Comments

2023/09/30

02:36 UTC

02:36 UTC

0

I'm in **Visualizing Data in 2D and 3D > Customizing Plot Properties > (2/3) Specifying Color**

I'm asked to: "Plot the data with the "Color" property set to the RGB vector [0.5 0.6 0]."

The code I wrote is:

plot(x,y,"Color",[0.5 0.6 0])

But it says that the line color isn't set correctly, after checking solution that MATLAB expect the code it shows is:

plot(x,y,"Color",[0.5 0.6 0])

Yet, it still says that the answer is incorrect, I think MATLAB now uses hex values, but what would that value be in hex?

7 Comments

2023/09/30

00:58 UTC

00:58 UTC

2

Hey, so I'm having trouble with plotting an exponential function on a graph. So, every time I try to run my code, I end up with a straight line on my graph. Does anyone how can I fix that?

A=1;

r1=input('Enter the value of r1:');

r2=input('Enter the value of r2:');

T1=input('Enter the beginning value of T:');

T2=input('Enter the ending value of T:');

E1=A*exp(-(r1*T1)); %Values Of First Constant

E2=A*exp(-(r1*T2));

G1=A*exp(-(r2*T1)); %Values Of Second Constant

G2=A*exp(-(r2*T2));

x=[T1 T2];

y1=[E1 E2];

y2=[G1 G2];

plot(x,y1,'r*:')

hold on

plot(x,y2)

xlabel('Time')

ylabel('Decay')

title('Decay Function')

grid on

(Here's my code)

3 Comments

2023/09/29

19:40 UTC

19:40 UTC

2

How would I code a 5x5 nonogram puzzle? I understand I have to loop through all possible permutations but I’m not sure how to do that.

3 Comments

2023/09/29

17:11 UTC

17:11 UTC

0

Trying to log in to my University linked account and am stuck in an infinite loop, enter username -> takes me to a create profile page. Initially there is no email box, so hit continue then it says add email. Hit refresh and an email box appears again. Put in my email and it says “already exists, log in or choose a new email. So if I click “log in”, I go to the start of the loop again.

2 Comments

2023/09/29

06:43 UTC

06:43 UTC

4

I'm trying to draw a MATLAB plot while using LaTeX formulas in MATLAB R2023a, but I can't display Chinese characters and LaTeX formulas at the same time, my code goes like this:

```
clc; clear; close all;
s=5000000;
x=1:s; y=cos(x);
y=cumsum(y);
figure
plot(x,y,'.')
title('级数$f=\sum\limits_{k=1}^n cosk$','Interpreter','latex')
```

but my plot looks like this:

I want to show them at the same time.

I tried to modify the `mxdom2latex.xsl`

:

```
<xsl:template match="mscript">
% This LaTeX was auto-generated from MATLAB code.
% To make changes, update the MATLAB code and republish this document.
\documentclass{article}
\usepackage{graphicx}
\usepackage{color}
\usepackage{ctex} % the only one statement that I added
\sloppy
\definecolor{lightgray}{gray}{0.5}
\setlength{\parindent}{0pt}
\begin{document}
```

But it does not make sense.

0 Comments

2023/09/29

06:41 UTC

06:41 UTC

0

What are the best options for using Matlab code Snippets in the Matlab Editor? I see on FileExchange that there are some third-party options. Recently, I installed the plugin Pieces to handle Snippets for VS Code. I could put Matlab Snippets in another App like Obsidian MD, copy/paste them into Matlab Editor, or use another tool. I need all this for MacOS Ventura or now Sonoma. Why does Matlab Editor not already have a Snippets feature? It may not be difficult. -Thanks.

5 Comments

2023/09/29

01:19 UTC

01:19 UTC

1

I'm new to MATLAB (Literally a few days). I wanted to know If there is any way I can run a formula that I have with the distances from a 3D scan that was exported to point cloud. (This question might not make sense, so please ask me if you need any clarification from me)

3 Comments

2023/09/28

18:12 UTC

18:12 UTC

3

Does anyone have any websites or book pdfs or anything really that has practice questions? anywhere i look the questions are either too easy or in a foreign language. i need practice questions about replacing columns/rows, finding the mean, finding the average of matrices as well as for, if and while loops. please help.

9 Comments

2023/09/28

14:54 UTC

14:54 UTC

2

Hi,

I'm trying to run some matlab code in version 2016B. It fails at line 8. From some rudimentary research I see that this new property validation syntax is from a later version of MATLAB. How do I make it compatible with my version. I deleted the size validation `(1,1)`

and it works but I don't know what the side effects will be

```
1 classdef Testsystem < handle
2 % Testsystem is the basis class for a test system.
3
4 % T=TESTSYSTEM(foo,'System');
5 properties
6 name
7 foo=struct([])
8 bar (1,1) Dynamics.Test.Model
```

9 Comments

2023/09/28

11:24 UTC

11:24 UTC

3

Hello everyone, I would really appreciate your help in this problem.

I'm intending to simulate Calcium oscillations according to the mathematical model showed in the image (I'm also attaching an image of how the graph should look like), but I'm getting a complete different graph. Does anyone could help me for knowing what do I'm doing wrong?

```
function f_val = low_CaFun(t, y)
% define constants
a = 0.185; % ER-to-cytoplasm volume ratio
B_t = 0; % total concentration of cytoplasmic Ca2+ buffer
C_o = 1700; % extracellular Ca2+ concentration
k_a = 0.3; % dissociation constant for Ca2+ activation of Ca2+ release
k_e = 0.3; % activation constant for Ca2+ efflux
k_i = 0.8; % dissociation constant for Ca2+ inactivation of Ca2+ release
k_u = 0.2; % activation constant for Ca2+ uptake
n = 0; %Hill constant for Ca2+ inhibition of Ca2+ release
v_a = 1/10; % association rate constant of Ca2+ to cytoplasmic buffer
v_d = 1/10; % dissociation rate constant of Ca2+ from cytoplasmic buffer
v_e = 0.2; % max Ca2+ efflux rate
v_i = 1/18; % rate constant for Ca2+ influx
v_l = 1/0.1; % rate constant for Ca2+ leak from ER
v_r = 1/4; % rate constant for Ca2+ leak from ER
v_u = 15; % max Ca2+ uptake rate
% define variables
C_c = y(1);
C_e = y(2);
B_b = y(3);
% define auxiliary equations
V_r = (v_l + v_r*((C_c^3)/(C_c^3 + k_a^3))*((k_i^n)/(C_c^n + k_i^n)))*(C_e - C_c);
V_u = v_u*((C_c^2)/(C_c^2 + k_u^2));
V_i = v_i*(C_o - C_c);
V_e = v_e*((C_c^2)/(C_c^2 + k_e^2));
V_b = v_a*(B_t - B_b)*C_c - v_d*B_b;
% define derivatives
dC_c = a*(V_r - V_u) + (V_i - V_e) - V_b;
dC_e = V_u - V_r;
dB_b = V_b;
f_val(1, 1) = dC_c;
f_val(2, 1) = dC_e;
f_val(3, 1) = dB_b;
```

And this one is the code for plotting. I'm using `ode45`

for solving the equation:

```
clc;
clear variables;
close all;
% solve low Ca+ ion oscilation system
y0 = [0; 0; 0];
tSpan = [0 10];
[tSol, ySol] = ode45(@(t, y) low_CaFun(t, y), tSpan, y0);
figure(1);
plot(tSol, ySol(:, 1), LineWidth = 2);
grid on;
hold on;
plot(tSol, ySol(:, 2), LineWidth = 2);
plot(tSol, ySol(:, 3), LineWidth = 2);
```

3 Comments

2023/09/28

09:18 UTC

09:18 UTC

2

I have some data for a dynamic system where the load was measured with respect to time, but the time interval is not constant. I want to produce a plot that shows amplitude vs frequency to find which frequencies mostly compose the data trace. How can I do this?

3 Comments

2023/09/28

06:10 UTC

06:10 UTC

3 Comments

2023/09/28

05:04 UTC

05:04 UTC

7

I'm just learning matlab and learned that in matlab matrices are traversed column-wise (vertically) and not row-wise (horizontally) which kind of bugged me. So I started trying to find a way such that if I wanted to retrieve a value in a matrix using its row-wise index, I can just plug the row-wise index into a certain expression or formula to get it its index column-wise. Of course an easy way to retrieve the value is to just transpose the matrix and use the row-wise index, but I still wanted to derive an expression without having to transpose the matrix. Here it is:

```
if M is an m*n matrix, then
M'(b) = M(m * mod(b - 1, n) + floor((b - 1) / n) + 1)
where b is the row-wise index of an element in M
```

Just thought it's cool and wanted to share

5 Comments

2023/09/27

22:40 UTC

22:40 UTC

0

There's a block from the Simscape library called Three-Phase V-I Measurement, with 3 wires (ABC). I would like to use it with a three-phase system that has 4 wires (ABCN, 3 phases and 1 neutral). How should I go about this?

I suppose the best way is to create a custom block. I was reading this documentation, but I was wondering if there's some type of S-function written for the block that alredy exists so I can understand how it works better and I write my own code for my modified block.

0 Comments

2023/09/27

19:08 UTC

19:08 UTC

0

hi everyone one i'm doing a predictive algorithm to find DFS using Cox regression, i first used LASSO regression to select the predictive variables, now i'm using the c-index to evaluate the predictive accuracy, and it's always equals to 1 and I can't understand why(I tried to reduce the numbers of variables just to see if it could change but it didnt) can someone help me? it will be so much appreciated, thanks

0 Comments

2023/09/27

18:12 UTC

18:12 UTC

1

The assigment is:

"Write a function filterRange(arr, a, b) that gets an array arr and removes the elements with values higher or equal to a and lower or equal to b and return a result as an array.

The function should not modify the array. It should return the new array."

I've been trying to make it work with a while loop but I just can't get it working.

10 Comments

2023/09/27

07:46 UTC

07:46 UTC

5

I want a neural network that tells me whether a point in my measurement data is a peak or not. There should be a list of 'possible peaks' as input. I would then always pass on one of the location of the possible peaks and all measuring points +-200 around the peak and would like to have a number between 1 and 0 as an answer as to how sure it is that it is a peak. I already have measurement data where all real peaks were found. My question would be, is something like this possible, is it worth it and are there examples of something like this somewhere, because I'm a beginner with neural networks.

4 Comments

2023/09/27

06:04 UTC

06:04 UTC

3

Hi,

I am not the expert here at all. But I do have the group truth (data) of a car driving on a semi circular path.

What is a good approach to do a simulated version of a car driving on a path to compare it with the ground truth data. The information available are latitude and longitude and yaw angles and heading/ pitch and roll.

I’m mostly interested in simulink or any other add on of matlab. It is not required to have a matlab coding part to it so I would avoid it.

Anything can help to figure out a way to do this.

8 Comments

2023/09/27

03:41 UTC

03:41 UTC

3

Hi everyone,

I know it's simple, but I'm absolutely stuck on the first step of my code.

My first line is supposed to allow the user to set the directory for which all of the next steps in the code will be performed, so I wrote;

**Cond = uigetdir**

I then want to perform a 'for loop' on all of the subfolders in the folder, "Cond".

- Am I even doing the first step correctly? It doesn't seem to get set as the working directory because if I enter "dir", it shows an actual directory in a matrix format, and if I enter "Cond" it lists the file path as a string. If I'm doing it incorrectly, what would be the proper way?
- What is the correct way to then identify all subfolders in the working directory?

Thanks everyone. Very new in matlab.

12 Comments

2023/09/26

23:47 UTC

23:47 UTC

0

Homework help:

So i have to do a fixed effects regression for uni and I'm failing with stacking my data. I have 8 files that I want to put together into 1 new file for this regression and my code files each time. Anyone up for it? I'd share the files via onedrive link. I have a code generated by chat gpt and tried to fix it on my own but I can't seem to find the mistake. Neither does chatgpt (our Prof wants us to use chatgpt)

** edit: I downloaded the data as yearly data to get around the reducing part. Not sure if it will be easier now

Also, I am happy for any help, but I can't afford to pay 50 to even $100 that I've been asked. I'm not looking for someone to do my assignment for me, but some hints that can help me.

this is the code I am using:

clear all; clc;

% Pfad zur Excel-Datei filePath = 'BoardSize.xlsx';

% Lesen Sie die Daten aus der Excel-Datei data = xlsread(filePath);

% Ermitteln Sie die Größe des Daten-Arrays [numRows, numCols] = size(data);

% Geben Sie die Range aus fprintf('Die Range der Excel-Datei %s ist %d Zeilen x %d Spalten.\n', filePath, numRows, numCols);

% Pfad zu den Excel-Dateien filePaths = {'BoardGenderDiversityPercent.xlsx', 'BoardSize.xlsx', 'CommonEquity.xlsx', 'MarketCapitalization.xlsx', 'NetSalesOrRevenue.xlsx', 'ROA.xlsx', 'TotalLiabilities.xlsx'};

% Initialisieren Sie eine leere Zelle für die kombinierten Daten combinedData = {};

% Schleife durch die Dateien und lesen Sie die Daten ein for i = 1:numel(filePaths) % Lesen Sie die Daten aus der aktuellen Datei data = xlsread(filePaths{i}, 'A2:BJA1421'); % Passen Sie den Bereich an Ihre Dateien an

```
% Fügen Sie die Daten zur kombinierten Zelle hinzu
combinedData = [combinedData, data];
```

end

% Erstellen Sie eine neue Excel-Datei outputFile = 'KombinierteDatei.xlsx';

% Erstellen Sie eine Matrix für die Ausgabe, in der die Unternehmen in Spalte A und die Jahre in Spalte B stehen outputMatrix = combinedData; % Include all columns

% Schreiben Sie die Daten in die Excel-Datei xlswrite(outputFile, outputMatrix, 'Sheet1');

% Hinweis: Wenn xlswrite nicht funktioniert, können Sie stattdessen writematrix verwenden (ab MATLAB R2019b) % writematrix(outputMatrix, outputFile);

8 Comments

2023/09/26

22:01 UTC

22:01 UTC

0

Variable k has an incorrect value.

The submission must contain the following functions or keywords: subs

%Setup the variables U(t) as the function of Temperature over a period of time t, and k that will be used in the program.

%Find also the derivative of U(t) and set as dU

syms t;

syms k;

syms U(t);

syms dU(t);

%Initial Conditions

cond1=U(0)==165;

cond2=U(10)==150;

Ta=35; %Ambient Temperature

Ufinal =70; %Final Temperature

%Set the differential equation model as eqn1;

eqn1=diff(U,t)-k*(U-Ta)==0;

%Find k1 and k2, by solving the initial value problem eqn1 using cond1 and cond2, respectively.

% solution using condition 1

Usol1(t,k)=dsolve(eqn1,cond1);

% solution using condition 2

Usol2(t,k)=dsolve(eqn1,cond2);

%Solve for k by equating k1 and k2 at t=0. Save results as k.

Sol(k)=Usol1(0,k)-Usol2(0,k);

% make form of equation

eqn=Sol(k)==0;

% Solve for k numerically

k_guess = 0.1; % Initial guess for k

k_value = fsolve(@(k) double(Sol(k)), k_guess);

fprintf("Value of k is %f\n", k_value);

%Solve the eqn1 using the acquired value of k and using Initial value cond1.

%Solving k

r=solve(eqn);

fprintf("Value of k is \n");

disp(r);

%Let the Usoln be equal to Ufinal. Solve the equation and save your answer as tfinal

% original function U(t)

Usoln(t)=Usol1(t,r);

eqn=Usoln(t)==Ufinal;

tfinal=(solve(eqn));

fprintf("At time %f temperature is 70F\n",tfinal);

x=0:.2:tfinal+20;

y=Usoln(x);

% Plot the equation: Use the Title=Cake Temperature, XValue=Time (in Minutes), YValue=Temperature (F)

Title="Cake Temperature";

XValue="Time (in Minutes)";

YValue="Temperature (F)";

plot(x,y);

hold on;

title(Title);

xlabel(XValue);

ylabel(YValue);

plot(0,Usoln(0),"r*");

plot(tfinal,Usoln(tfinal),"r*");

hold off;

1 Comment

2023/09/26

18:29 UTC

18:29 UTC

2

The Challenge

If you are a student and you have a very innovative project you are building with Simulink, you have a chance to win up to $1000! All you need to do is submit a short original video that shows what you’ve accomplished using Simulink. The key to winning is to show your creativity and to use Simulink. Check out the recent Simulink Student Challenge winners for inspiration.

The winning hub motor hybrid design from 2022

- December 12, 2023: Submission deadline (
**1 p.m. ET**) - December 18, 2023–January 18, 2024: Judging
- January 31, 2024: Winners announced

More Details:

https://www.mathworks.com/academia/student-challenge/simulink-student-challenge-2023.html

0 Comments

2023/09/26

14:35 UTC

14:35 UTC

3

I have four matrices that are each 8 by 8: matrix P, matrix Q, matrix R, and matrix G. I have a certain algorithm (I wont go in to too much details about it because its too complicated with multiple files) that depends on those four matrices and uses them to output a single column of values for me. I also have what I call the perfect output, which is what I desire the output single column to look like. Now my question is: How can I use MATLAB to tune those 4 matrices in order for the output column to match approximately the perfect output column.

3 Comments

2023/09/26

12:33 UTC

12:33 UTC

1

I need to make a graph of a speed bump, with x and y axes in meters. Signal builder has time on the x axis, can I change that?

5 Comments

2023/09/26

08:40 UTC

08:40 UTC

0

I will post a photo of the assignment but basically I am very new to Matlab and have been really struggling with the course on it. For this assignment there is a Taylor polynomial where a user has to input an x value and a number of terms, but I cannot figure out how to do this exactly, it also mentioned using loops. There is also a second part relating to a triangle that I haven’t looked into yet because I haven’t figured out the first part. Literally any help would be appreciated.

5 Comments

2023/09/25

23:48 UTC

23:48 UTC