Category: Matlab
Category Archives: Matlab
How I organize and insert NIR dataset for Classification Learner.
Hello,
I currently research the field of near-infrared spectroscopy (NIR), mainly in the analysis of the spectra of polymeric materials. I would like to make a system for classifying these spectra by machine learning. Literature indicates the APP Classification Leaner and its models to perform the training of the spectra. However, I’m having trouble inserting the spectra sheet (containing wavelength and absorbance values). Being new to Matlab, I don’t know how to organize these spreadsheets with different values, because the wavelength is constant for the different samples, but the absorbance varies for them. My idea is to classify the spectra for the different materials. How could I organize the spreadsheet and develop the training?
If anyone can help me with a tutorial or quick step by step, I would be extremely grateful.
Thanks.Hello,
I currently research the field of near-infrared spectroscopy (NIR), mainly in the analysis of the spectra of polymeric materials. I would like to make a system for classifying these spectra by machine learning. Literature indicates the APP Classification Leaner and its models to perform the training of the spectra. However, I’m having trouble inserting the spectra sheet (containing wavelength and absorbance values). Being new to Matlab, I don’t know how to organize these spreadsheets with different values, because the wavelength is constant for the different samples, but the absorbance varies for them. My idea is to classify the spectra for the different materials. How could I organize the spreadsheet and develop the training?
If anyone can help me with a tutorial or quick step by step, I would be extremely grateful.
Thanks. Hello,
I currently research the field of near-infrared spectroscopy (NIR), mainly in the analysis of the spectra of polymeric materials. I would like to make a system for classifying these spectra by machine learning. Literature indicates the APP Classification Leaner and its models to perform the training of the spectra. However, I’m having trouble inserting the spectra sheet (containing wavelength and absorbance values). Being new to Matlab, I don’t know how to organize these spreadsheets with different values, because the wavelength is constant for the different samples, but the absorbance varies for them. My idea is to classify the spectra for the different materials. How could I organize the spreadsheet and develop the training?
If anyone can help me with a tutorial or quick step by step, I would be extremely grateful.
Thanks. nir, classification learner MATLAB Answers — New Questions
how to generate correct logical mask of the size of shape file?
i am using following code to generate logical mask
function croppedimg = cropimage(data, R, shapefile)
% Load the shapefile and retrieve its info
S = shaperead(shapefile);
% Shapefile projections
info = shapeinfo(shapefile);
crs = info.CoordinateReferenceSystem;
[S.lon,S.lat] = projinv(crs,S.X,S.Y);
% read and reproject image file
p = R.ProjectedCRS;
[x,y] = worldGrid(R);
[lon,lat] = projinv(p,x,y);
% Create a logical mask
% Approach 1: Using ‘inpolygon’ function
xq = lon(:);
yq = lat(:);
in = inpolygon(xq,yq,S.lon,S.lat);
logical_mask = reshape(in,size(lon));
% Debugging: Display the logical mask summary
disp([‘Total number of pixels inside polygon: ‘, num2str(numel(logical_mask))]);
disp([‘Total number of pixels inside image: ‘, num2str(numel(data))]);
However it is showing the
Total number of pixels inside polygon: 16982229
Total number of pixels inside image: 16982229
please suggest me how to create correct logical mask of the size of shape file.
kuldeepi am using following code to generate logical mask
function croppedimg = cropimage(data, R, shapefile)
% Load the shapefile and retrieve its info
S = shaperead(shapefile);
% Shapefile projections
info = shapeinfo(shapefile);
crs = info.CoordinateReferenceSystem;
[S.lon,S.lat] = projinv(crs,S.X,S.Y);
% read and reproject image file
p = R.ProjectedCRS;
[x,y] = worldGrid(R);
[lon,lat] = projinv(p,x,y);
% Create a logical mask
% Approach 1: Using ‘inpolygon’ function
xq = lon(:);
yq = lat(:);
in = inpolygon(xq,yq,S.lon,S.lat);
logical_mask = reshape(in,size(lon));
% Debugging: Display the logical mask summary
disp([‘Total number of pixels inside polygon: ‘, num2str(numel(logical_mask))]);
disp([‘Total number of pixels inside image: ‘, num2str(numel(data))]);
However it is showing the
Total number of pixels inside polygon: 16982229
Total number of pixels inside image: 16982229
please suggest me how to create correct logical mask of the size of shape file.
kuldeep i am using following code to generate logical mask
function croppedimg = cropimage(data, R, shapefile)
% Load the shapefile and retrieve its info
S = shaperead(shapefile);
% Shapefile projections
info = shapeinfo(shapefile);
crs = info.CoordinateReferenceSystem;
[S.lon,S.lat] = projinv(crs,S.X,S.Y);
% read and reproject image file
p = R.ProjectedCRS;
[x,y] = worldGrid(R);
[lon,lat] = projinv(p,x,y);
% Create a logical mask
% Approach 1: Using ‘inpolygon’ function
xq = lon(:);
yq = lat(:);
in = inpolygon(xq,yq,S.lon,S.lat);
logical_mask = reshape(in,size(lon));
% Debugging: Display the logical mask summary
disp([‘Total number of pixels inside polygon: ‘, num2str(numel(logical_mask))]);
disp([‘Total number of pixels inside image: ‘, num2str(numel(data))]);
However it is showing the
Total number of pixels inside polygon: 16982229
Total number of pixels inside image: 16982229
please suggest me how to create correct logical mask of the size of shape file.
kuldeep how to generate correct logical mask ? MATLAB Answers — New Questions
Simulink filter using frequency response transfer function
Hi,
My main problem is this: I’m building a fiber optical communication system using simulink.
As a source, I use a bernoulli generator, then this signal runs to a low pass filter and the exit is the signal equivalent to a signal that comes off a led, so the emission part is done.
The problems begins at the transmission channel. I want to do a filter that simulates the dispersion effect in the fiber (only chromatic dispersion), but I don’t know how. I only have a transfer functions like exp(-j*alpha*f.^2) and I don’t know what to do with this. What’s the right procedure to implement this kind of t.f. in a analog filter at the simulink?
Any help is welcome.
Kind regardsHi,
My main problem is this: I’m building a fiber optical communication system using simulink.
As a source, I use a bernoulli generator, then this signal runs to a low pass filter and the exit is the signal equivalent to a signal that comes off a led, so the emission part is done.
The problems begins at the transmission channel. I want to do a filter that simulates the dispersion effect in the fiber (only chromatic dispersion), but I don’t know how. I only have a transfer functions like exp(-j*alpha*f.^2) and I don’t know what to do with this. What’s the right procedure to implement this kind of t.f. in a analog filter at the simulink?
Any help is welcome.
Kind regards Hi,
My main problem is this: I’m building a fiber optical communication system using simulink.
As a source, I use a bernoulli generator, then this signal runs to a low pass filter and the exit is the signal equivalent to a signal that comes off a led, so the emission part is done.
The problems begins at the transmission channel. I want to do a filter that simulates the dispersion effect in the fiber (only chromatic dispersion), but I don’t know how. I only have a transfer functions like exp(-j*alpha*f.^2) and I don’t know what to do with this. What’s the right procedure to implement this kind of t.f. in a analog filter at the simulink?
Any help is welcome.
Kind regards simulink, optical dispersion MATLAB Answers — New Questions
Why does App Designer include the full file path when packaging external helper functions?
I am trying to create a GUI for some existing code I wrote using the MATLAB App Designer. The app relies on some external helper functions that I wrote in MATLAB program files and they are correctly identified as necessary to include; however, when packaged it includes the entire file path of the matlab function files within the installed package. This means that after installing the app, for example, tallySum.m ends up stored in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/Users/rhysg/Documents/YPGRA/TIRF_ProcessingCode/tallySum.m" instead of just placing it in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/tallySum.m"
This doesn’t cause functional problems but it does not seem intended and I was wondering if it could be avoided. Other than copying all the functions directly into the app is there a way to fix this? Is there a reason it functions in this way? Is there somewhere else to look for information on this?
Thanks in advance.I am trying to create a GUI for some existing code I wrote using the MATLAB App Designer. The app relies on some external helper functions that I wrote in MATLAB program files and they are correctly identified as necessary to include; however, when packaged it includes the entire file path of the matlab function files within the installed package. This means that after installing the app, for example, tallySum.m ends up stored in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/Users/rhysg/Documents/YPGRA/TIRF_ProcessingCode/tallySum.m" instead of just placing it in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/tallySum.m"
This doesn’t cause functional problems but it does not seem intended and I was wondering if it could be avoided. Other than copying all the functions directly into the app is there a way to fix this? Is there a reason it functions in this way? Is there somewhere else to look for information on this?
Thanks in advance. I am trying to create a GUI for some existing code I wrote using the MATLAB App Designer. The app relies on some external helper functions that I wrote in MATLAB program files and they are correctly identified as necessary to include; however, when packaged it includes the entire file path of the matlab function files within the installed package. This means that after installing the app, for example, tallySum.m ends up stored in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/Users/rhysg/Documents/YPGRA/TIRF_ProcessingCode/tallySum.m" instead of just placing it in "/Users/rhysg/Library/Application Support/MathWorks/MATLAB Add-Ons/Apps/NNB_GUI/tallySum.m"
This doesn’t cause functional problems but it does not seem intended and I was wondering if it could be avoided. Other than copying all the functions directly into the app is there a way to fix this? Is there a reason it functions in this way? Is there somewhere else to look for information on this?
Thanks in advance. app designer MATLAB Answers — New Questions
How to insert an image into a specific Excel cell?
In Excel, I can place an image into a specific cell using Insert -> Pictures -> Place in Cell; this inserts the image into the cell, not floating over the cell. Can the same thing be done from MATLAB using ActiveX? Note I already have working code to insert a floating image in any desired location. What I really need to do is to insert it into a cell of my choosing.In Excel, I can place an image into a specific cell using Insert -> Pictures -> Place in Cell; this inserts the image into the cell, not floating over the cell. Can the same thing be done from MATLAB using ActiveX? Note I already have working code to insert a floating image in any desired location. What I really need to do is to insert it into a cell of my choosing. In Excel, I can place an image into a specific cell using Insert -> Pictures -> Place in Cell; this inserts the image into the cell, not floating over the cell. Can the same thing be done from MATLAB using ActiveX? Note I already have working code to insert a floating image in any desired location. What I really need to do is to insert it into a cell of my choosing. insert image, excel MATLAB Answers — New Questions
identify model parameters and data (g = Gm).
I have a problem, namely to identify model parameters and data (g = Gm).
I’ve done it in my notebook, but I want to write a matlab script for this and I’m struggling on how to write the matrix G the right way in matlab.
This is how I write G in my notebook:
1111000000000000
0000111100000000
0000000011110000
0000000000001111
1000100010001000
0100010001000100
0010001000100010
0001000100010001I have a problem, namely to identify model parameters and data (g = Gm).
I’ve done it in my notebook, but I want to write a matlab script for this and I’m struggling on how to write the matrix G the right way in matlab.
This is how I write G in my notebook:
1111000000000000
0000111100000000
0000000011110000
0000000000001111
1000100010001000
0100010001000100
0010001000100010
0001000100010001 I have a problem, namely to identify model parameters and data (g = Gm).
I’ve done it in my notebook, but I want to write a matlab script for this and I’m struggling on how to write the matrix G the right way in matlab.
This is how I write G in my notebook:
1111000000000000
0000111100000000
0000000011110000
0000000000001111
1000100010001000
0100010001000100
0010001000100010
0001000100010001 #help MATLAB Answers — New Questions
Fit a custom made function to a certain trend within data from a matrix
Dear all,
I have been struggling for a while with the two issues that I show you below.
I have a matrix which represents the image of a pixelated neutron detector. The units of such a matrix is Count/minute. If I plot the matrix with the command surface(X, Y, Z), being Z the matrix, I get the following figure:
In this figure we can see two different trends: the x=y line (plus its width), which is what we call the "Specular Ridge", and a tiny contribution given by the white dashed line, which is what we call the "Zemann Splitting". The Zemann splitting is given by the equation y = sqrt(x^2 – (1.47e-7*H*L^2)), where H is the magnetic field and L is the wavelength of the nuetrons (5.183 AA in my case).
I would like to find the optimum H which fits best to the data inside the red circle by using the above mentioned equation (H should be something like 6-7). And later I would like to make a ROI (Region Of Interest) to count how many counts lay within such area.
I have attached the matrix (file 00607_UD_subplot.txt) and X and Y coordinates (files 00607_UD_xcoordinates.txt and 00607_UD_ycoordinates.txt).
The code to visualize the figure is the following:
A = load(‘00607_UD_subplot.txt’);
X = load(‘00607_UD_xcoordinates.txt’);
Y = load(‘00607_UD_ycoordinates.txt’);
surface(X, Y, A)
axis square
colormap(map);
caxis([5e-4 100])
set(gca,’colorscale’,’log’)
hold on
plot(X, sqrt((X.^2) – (1.47e-7*6.5*5.183^2)), ‘Color’,’white’,’LineStyle’,’–‘, ‘LineWidth’, 2)
xlabel(‘alpha_{i} [rad]’, ‘fontsize’, 18);
ylabel(‘alpha_{f} [rad]’, ‘fontsize’, 18);
cb1 = colorbar;
cb1.Label.String = ‘Neutron Intensity (CTS/MIN)’;
cb1.FontSize = 16;
cb1.Label.FontSize = 20;
cb1.LineWidth = 1.5;
Any help / suggestion would be helpful and very welcomedl!!!
Cheers,
Jose.Dear all,
I have been struggling for a while with the two issues that I show you below.
I have a matrix which represents the image of a pixelated neutron detector. The units of such a matrix is Count/minute. If I plot the matrix with the command surface(X, Y, Z), being Z the matrix, I get the following figure:
In this figure we can see two different trends: the x=y line (plus its width), which is what we call the "Specular Ridge", and a tiny contribution given by the white dashed line, which is what we call the "Zemann Splitting". The Zemann splitting is given by the equation y = sqrt(x^2 – (1.47e-7*H*L^2)), where H is the magnetic field and L is the wavelength of the nuetrons (5.183 AA in my case).
I would like to find the optimum H which fits best to the data inside the red circle by using the above mentioned equation (H should be something like 6-7). And later I would like to make a ROI (Region Of Interest) to count how many counts lay within such area.
I have attached the matrix (file 00607_UD_subplot.txt) and X and Y coordinates (files 00607_UD_xcoordinates.txt and 00607_UD_ycoordinates.txt).
The code to visualize the figure is the following:
A = load(‘00607_UD_subplot.txt’);
X = load(‘00607_UD_xcoordinates.txt’);
Y = load(‘00607_UD_ycoordinates.txt’);
surface(X, Y, A)
axis square
colormap(map);
caxis([5e-4 100])
set(gca,’colorscale’,’log’)
hold on
plot(X, sqrt((X.^2) – (1.47e-7*6.5*5.183^2)), ‘Color’,’white’,’LineStyle’,’–‘, ‘LineWidth’, 2)
xlabel(‘alpha_{i} [rad]’, ‘fontsize’, 18);
ylabel(‘alpha_{f} [rad]’, ‘fontsize’, 18);
cb1 = colorbar;
cb1.Label.String = ‘Neutron Intensity (CTS/MIN)’;
cb1.FontSize = 16;
cb1.Label.FontSize = 20;
cb1.LineWidth = 1.5;
Any help / suggestion would be helpful and very welcomedl!!!
Cheers,
Jose. Dear all,
I have been struggling for a while with the two issues that I show you below.
I have a matrix which represents the image of a pixelated neutron detector. The units of such a matrix is Count/minute. If I plot the matrix with the command surface(X, Y, Z), being Z the matrix, I get the following figure:
In this figure we can see two different trends: the x=y line (plus its width), which is what we call the "Specular Ridge", and a tiny contribution given by the white dashed line, which is what we call the "Zemann Splitting". The Zemann splitting is given by the equation y = sqrt(x^2 – (1.47e-7*H*L^2)), where H is the magnetic field and L is the wavelength of the nuetrons (5.183 AA in my case).
I would like to find the optimum H which fits best to the data inside the red circle by using the above mentioned equation (H should be something like 6-7). And later I would like to make a ROI (Region Of Interest) to count how many counts lay within such area.
I have attached the matrix (file 00607_UD_subplot.txt) and X and Y coordinates (files 00607_UD_xcoordinates.txt and 00607_UD_ycoordinates.txt).
The code to visualize the figure is the following:
A = load(‘00607_UD_subplot.txt’);
X = load(‘00607_UD_xcoordinates.txt’);
Y = load(‘00607_UD_ycoordinates.txt’);
surface(X, Y, A)
axis square
colormap(map);
caxis([5e-4 100])
set(gca,’colorscale’,’log’)
hold on
plot(X, sqrt((X.^2) – (1.47e-7*6.5*5.183^2)), ‘Color’,’white’,’LineStyle’,’–‘, ‘LineWidth’, 2)
xlabel(‘alpha_{i} [rad]’, ‘fontsize’, 18);
ylabel(‘alpha_{f} [rad]’, ‘fontsize’, 18);
cb1 = colorbar;
cb1.Label.String = ‘Neutron Intensity (CTS/MIN)’;
cb1.FontSize = 16;
cb1.Label.FontSize = 20;
cb1.LineWidth = 1.5;
Any help / suggestion would be helpful and very welcomedl!!!
Cheers,
Jose. curve fitting, region of interest MATLAB Answers — New Questions
Enter table with conditional limits and able to interpolate
I would like to enter the following numerical table with conditional limits and be able to interpolate within the values provided in the table. I was able to enter the rows x columns but I do not know what can I do for those values that are less than or larger than. How can <= or >= be taken care of? I believe interp2 should be used to find intermediate values for lets say h/L=12 degrees and h/L =0.35 for example. Please advise.I would like to enter the following numerical table with conditional limits and be able to interpolate within the values provided in the table. I was able to enter the rows x columns but I do not know what can I do for those values that are less than or larger than. How can <= or >= be taken care of? I believe interp2 should be used to find intermediate values for lets say h/L=12 degrees and h/L =0.35 for example. Please advise. I would like to enter the following numerical table with conditional limits and be able to interpolate within the values provided in the table. I was able to enter the rows x columns but I do not know what can I do for those values that are less than or larger than. How can <= or >= be taken care of? I believe interp2 should be used to find intermediate values for lets say h/L=12 degrees and h/L =0.35 for example. Please advise. interpolation and table question MATLAB Answers — New Questions
Eventfilters with durations return wrong (amount of) rows?
Hi all, I have a question that’s either a case of "am I not understanding this right?" or a bug in eventfilters.
I’ve noticed 2 things: 1) event filters with durations seem to return the rows after the start of events, and 2) scaling the duration of events does not result in the expected scaling of the number of rows filtered.
For background, in reality I’m using this to mark the edges of TTL-pulses in datasets, but I made an example below that I think illustrates my point.
Running the following code:
% Create a 5s timetable with mock data.
test_table = timetable(seconds(linspace(1/1000, 5, 5000)).’, linspace(0, 1, 5000).’);
% Create an eventtable with 3 events at random time points and a duration
% equal to the table timestep.
test_times = seconds([1.101, 2.2, 3]);
labels = ["rising", "rising", "falling"];
delta_t = test_table.Properties.TimeStep;
lengths = repmat(1*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
% Associate events with timetable.
test_table.Properties.Events = test_events;
% Create a filter to determine the time of the rising edges.
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
% Display number of rows returned by the filter.
disp(height(test_rows));
% Display the times of the filtered rows.
disp(test_rows.Time);
So here I’m making a mock timetable of 5 seconds at 1000 Hz, with mock data in it, and 3 time events: two rising edges, and one falling edge. Each event is given a length of 1/1000s or 1 ms, which is equal to the timestep of the table. Then, I create an eventfilter to extract the rows of the time table at these edges.
Issue 1
The filter returns 2 rows as expected. However, the row times are 1.102 and 2.201, which are the row times after the rows in which the events begin according to the event table. This seems at odds with the description in the documentation for eventtable, which says that "Interval events happen during intervals that start at event times and include all times up to, but not including, the times at the end of the events." (emphasis mine). So shouldn’t these timed events return the row times 1.101 and 2.200 seconds?
As an aside, removing the EventLengths from the eventtable constructor returns the correct row times.
Issue 2
Second, for events with lengths larger than a single TimeStep, increasing the duration by a given factor does not always increase the number of returned rows by the same amount.
In this case, if I replace
lengths = repmat(1*delta_t, 1, 3);
with
lengths = repmat(50*delta_t, 1, 3);
and run the code again:
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
the number of filtered rows increases from 2 to 100, as expected.
However, increasing the duration of the events to 100 TimeSteps, changes the number of filtered rows to 199 instead of 200, which is what I was expecting.
lengths = repmat(100*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
This seems odd, given that both 50 and 100 TimeSteps should easily fit within the time vector of the table, are exact multiples of each other, do not overlap with other events and the length was based on the TimeStep property of the table.
I’ve locally tested the script in 2024a, but the code examples above ran in 2024b.Hi all, I have a question that’s either a case of "am I not understanding this right?" or a bug in eventfilters.
I’ve noticed 2 things: 1) event filters with durations seem to return the rows after the start of events, and 2) scaling the duration of events does not result in the expected scaling of the number of rows filtered.
For background, in reality I’m using this to mark the edges of TTL-pulses in datasets, but I made an example below that I think illustrates my point.
Running the following code:
% Create a 5s timetable with mock data.
test_table = timetable(seconds(linspace(1/1000, 5, 5000)).’, linspace(0, 1, 5000).’);
% Create an eventtable with 3 events at random time points and a duration
% equal to the table timestep.
test_times = seconds([1.101, 2.2, 3]);
labels = ["rising", "rising", "falling"];
delta_t = test_table.Properties.TimeStep;
lengths = repmat(1*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
% Associate events with timetable.
test_table.Properties.Events = test_events;
% Create a filter to determine the time of the rising edges.
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
% Display number of rows returned by the filter.
disp(height(test_rows));
% Display the times of the filtered rows.
disp(test_rows.Time);
So here I’m making a mock timetable of 5 seconds at 1000 Hz, with mock data in it, and 3 time events: two rising edges, and one falling edge. Each event is given a length of 1/1000s or 1 ms, which is equal to the timestep of the table. Then, I create an eventfilter to extract the rows of the time table at these edges.
Issue 1
The filter returns 2 rows as expected. However, the row times are 1.102 and 2.201, which are the row times after the rows in which the events begin according to the event table. This seems at odds with the description in the documentation for eventtable, which says that "Interval events happen during intervals that start at event times and include all times up to, but not including, the times at the end of the events." (emphasis mine). So shouldn’t these timed events return the row times 1.101 and 2.200 seconds?
As an aside, removing the EventLengths from the eventtable constructor returns the correct row times.
Issue 2
Second, for events with lengths larger than a single TimeStep, increasing the duration by a given factor does not always increase the number of returned rows by the same amount.
In this case, if I replace
lengths = repmat(1*delta_t, 1, 3);
with
lengths = repmat(50*delta_t, 1, 3);
and run the code again:
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
the number of filtered rows increases from 2 to 100, as expected.
However, increasing the duration of the events to 100 TimeSteps, changes the number of filtered rows to 199 instead of 200, which is what I was expecting.
lengths = repmat(100*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
This seems odd, given that both 50 and 100 TimeSteps should easily fit within the time vector of the table, are exact multiples of each other, do not overlap with other events and the length was based on the TimeStep property of the table.
I’ve locally tested the script in 2024a, but the code examples above ran in 2024b. Hi all, I have a question that’s either a case of "am I not understanding this right?" or a bug in eventfilters.
I’ve noticed 2 things: 1) event filters with durations seem to return the rows after the start of events, and 2) scaling the duration of events does not result in the expected scaling of the number of rows filtered.
For background, in reality I’m using this to mark the edges of TTL-pulses in datasets, but I made an example below that I think illustrates my point.
Running the following code:
% Create a 5s timetable with mock data.
test_table = timetable(seconds(linspace(1/1000, 5, 5000)).’, linspace(0, 1, 5000).’);
% Create an eventtable with 3 events at random time points and a duration
% equal to the table timestep.
test_times = seconds([1.101, 2.2, 3]);
labels = ["rising", "rising", "falling"];
delta_t = test_table.Properties.TimeStep;
lengths = repmat(1*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
% Associate events with timetable.
test_table.Properties.Events = test_events;
% Create a filter to determine the time of the rising edges.
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
% Display number of rows returned by the filter.
disp(height(test_rows));
% Display the times of the filtered rows.
disp(test_rows.Time);
So here I’m making a mock timetable of 5 seconds at 1000 Hz, with mock data in it, and 3 time events: two rising edges, and one falling edge. Each event is given a length of 1/1000s or 1 ms, which is equal to the timestep of the table. Then, I create an eventfilter to extract the rows of the time table at these edges.
Issue 1
The filter returns 2 rows as expected. However, the row times are 1.102 and 2.201, which are the row times after the rows in which the events begin according to the event table. This seems at odds with the description in the documentation for eventtable, which says that "Interval events happen during intervals that start at event times and include all times up to, but not including, the times at the end of the events." (emphasis mine). So shouldn’t these timed events return the row times 1.101 and 2.200 seconds?
As an aside, removing the EventLengths from the eventtable constructor returns the correct row times.
Issue 2
Second, for events with lengths larger than a single TimeStep, increasing the duration by a given factor does not always increase the number of returned rows by the same amount.
In this case, if I replace
lengths = repmat(1*delta_t, 1, 3);
with
lengths = repmat(50*delta_t, 1, 3);
and run the code again:
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
the number of filtered rows increases from 2 to 100, as expected.
However, increasing the duration of the events to 100 TimeSteps, changes the number of filtered rows to 199 instead of 200, which is what I was expecting.
lengths = repmat(100*delta_t, 1, 3);
test_events = eventtable(test_times, EventLabels = labels, EventLengths = lengths);
test_table.Properties.Events = test_events;
test_filter = eventfilter("rising");
test_rows = test_table(test_filter, :);
disp(height(test_rows));
This seems odd, given that both 50 and 100 TimeSteps should easily fit within the time vector of the table, are exact multiples of each other, do not overlap with other events and the length was based on the TimeStep property of the table.
I’ve locally tested the script in 2024a, but the code examples above ran in 2024b. time series, eventtable, timetable, matlab, eventfilter MATLAB Answers — New Questions
MATLAB Coder: How do I setup the environment variables on ARM targets to point to the ARM Compute Library?
I see a few deep learning networks supported for code generation using MATLAB Coder:
Deep Learning Networks and Layers Supported for C++ Code Generation
And I’ve seen the question here about building the ARM Compute Library:
MATLAB Coder: How do I build the ARM Compute Library for Deep Learning C++ code generation and deployment?
The next question I have is, how do I set the environment variables on ARM targets to point to the ARM Compute Library?I see a few deep learning networks supported for code generation using MATLAB Coder:
Deep Learning Networks and Layers Supported for C++ Code Generation
And I’ve seen the question here about building the ARM Compute Library:
MATLAB Coder: How do I build the ARM Compute Library for Deep Learning C++ code generation and deployment?
The next question I have is, how do I set the environment variables on ARM targets to point to the ARM Compute Library? I see a few deep learning networks supported for code generation using MATLAB Coder:
Deep Learning Networks and Layers Supported for C++ Code Generation
And I’ve seen the question here about building the ARM Compute Library:
MATLAB Coder: How do I build the ARM Compute Library for Deep Learning C++ code generation and deployment?
The next question I have is, how do I set the environment variables on ARM targets to point to the ARM Compute Library? neural network, deep learning, code generation, coder-tips, arm, arm cortex-a, arm compute library MATLAB Answers — New Questions
recover color on image
i am converted rgb color image to im2bw format and gray scale image.
after i am extracted the boundary then i want to stored the the colored image.
please tell how to manage the color then recover or apply color for gray scale image and im2bw imagei am converted rgb color image to im2bw format and gray scale image.
after i am extracted the boundary then i want to stored the the colored image.
please tell how to manage the color then recover or apply color for gray scale image and im2bw image i am converted rgb color image to im2bw format and gray scale image.
after i am extracted the boundary then i want to stored the the colored image.
please tell how to manage the color then recover or apply color for gray scale image and im2bw image image processing, digital image processing, image, image segmentation, image analysis MATLAB Answers — New Questions
Is giving a space after comma in functions the convention?
I more often see
y = pdf(‘t’, x, df);
than
y = pdf(‘t’,x,df);
That is, people often give a space after comma when writing the input arguments in a function. But then when indexing from an array like
array[1,2]
they do not do this. I also see this happening in books. So is this indeed a convention? If not, what is the comvention? Or are both just a matter of preference. But I doubt that preference is the case because I consistently see the above happening.I more often see
y = pdf(‘t’, x, df);
than
y = pdf(‘t’,x,df);
That is, people often give a space after comma when writing the input arguments in a function. But then when indexing from an array like
array[1,2]
they do not do this. I also see this happening in books. So is this indeed a convention? If not, what is the comvention? Or are both just a matter of preference. But I doubt that preference is the case because I consistently see the above happening. I more often see
y = pdf(‘t’, x, df);
than
y = pdf(‘t’,x,df);
That is, people often give a space after comma when writing the input arguments in a function. But then when indexing from an array like
array[1,2]
they do not do this. I also see this happening in books. So is this indeed a convention? If not, what is the comvention? Or are both just a matter of preference. But I doubt that preference is the case because I consistently see the above happening. syntax MATLAB Answers — New Questions
How does MATLAB generate the probability density function?
I am using the pdf function (https://nl.mathworks.com/help/stats/prob.normaldistribution.pdf.html) to just visuilize the pdf of the t statistic for teaching purposes. I am wondering how MATLAB generates this continous distrubtion. That is, this is the limiting distrbituion, so MATLAB should be taking many many random draws from the t distrubtion so that the frequency distribtuon converges to the pdf as the limiting distribtuon and looks all smooth, i.e. it does not look at all like a frequency distribution. But then how come that this happens so fast that I get the pdf immedaitly when I call the pdf function? Or is this not how MATLAB generates the pdf?I am using the pdf function (https://nl.mathworks.com/help/stats/prob.normaldistribution.pdf.html) to just visuilize the pdf of the t statistic for teaching purposes. I am wondering how MATLAB generates this continous distrubtion. That is, this is the limiting distrbituion, so MATLAB should be taking many many random draws from the t distrubtion so that the frequency distribtuon converges to the pdf as the limiting distribtuon and looks all smooth, i.e. it does not look at all like a frequency distribution. But then how come that this happens so fast that I get the pdf immedaitly when I call the pdf function? Or is this not how MATLAB generates the pdf? I am using the pdf function (https://nl.mathworks.com/help/stats/prob.normaldistribution.pdf.html) to just visuilize the pdf of the t statistic for teaching purposes. I am wondering how MATLAB generates this continous distrubtion. That is, this is the limiting distrbituion, so MATLAB should be taking many many random draws from the t distrubtion so that the frequency distribtuon converges to the pdf as the limiting distribtuon and looks all smooth, i.e. it does not look at all like a frequency distribution. But then how come that this happens so fast that I get the pdf immedaitly when I call the pdf function? Or is this not how MATLAB generates the pdf? pdf, function MATLAB Answers — New Questions
MATLAB – Read GRIB Data
Background:
I want to import meteorological data (wind speed, temperature as a function of position and altitude) in the GRIB-format into Matlab.
Status:
While googling I found this Matlab-Grib-Reader: <http://www.mathworks.com/matlabcentr…exchange/21579>
The Matlab Grib-Reader requires CDI libraries from here: <https://code.zmaw.de/projects/cdi/files>
The libraries must be compiled with the own machine, i used this terminal commands:
./configure CFLAGS=-fPIC CPPFLAGS=-fPIC –enable-shared
make
I copied the resulting libcdi.a library into the lib64 folder, and executed compile.m which gave me the following:
COMPILING cdi_varlist…
cdi_mx.c: In function ‘getLevel’:
cdi_mx.c:431: warning: incompatible implicit declaration of built-in function ‘modf’
Undefined symbols for architecture x86_64:
"_Warning", referenced from:
_getLevel in cdi_mx.o
(maybe you meant: _Warning_)
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
mex: link of ‘ "cdi_varlist.mexmaci64"’ failed.
Error using mex (line 206)
Unable to complete successfully.
Error in compile (line 15)
mex cdi_varlist.c cdi_mx.c -Iinclude -Llib64 -lcdi -lnetcdf
Who can help?
PS: Matlab 2012a, Mac OS X 10.8.2, Xcode 4.6Background:
I want to import meteorological data (wind speed, temperature as a function of position and altitude) in the GRIB-format into Matlab.
Status:
While googling I found this Matlab-Grib-Reader: <http://www.mathworks.com/matlabcentr…exchange/21579>
The Matlab Grib-Reader requires CDI libraries from here: <https://code.zmaw.de/projects/cdi/files>
The libraries must be compiled with the own machine, i used this terminal commands:
./configure CFLAGS=-fPIC CPPFLAGS=-fPIC –enable-shared
make
I copied the resulting libcdi.a library into the lib64 folder, and executed compile.m which gave me the following:
COMPILING cdi_varlist…
cdi_mx.c: In function ‘getLevel’:
cdi_mx.c:431: warning: incompatible implicit declaration of built-in function ‘modf’
Undefined symbols for architecture x86_64:
"_Warning", referenced from:
_getLevel in cdi_mx.o
(maybe you meant: _Warning_)
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
mex: link of ‘ "cdi_varlist.mexmaci64"’ failed.
Error using mex (line 206)
Unable to complete successfully.
Error in compile (line 15)
mex cdi_varlist.c cdi_mx.c -Iinclude -Llib64 -lcdi -lnetcdf
Who can help?
PS: Matlab 2012a, Mac OS X 10.8.2, Xcode 4.6 Background:
I want to import meteorological data (wind speed, temperature as a function of position and altitude) in the GRIB-format into Matlab.
Status:
While googling I found this Matlab-Grib-Reader: <http://www.mathworks.com/matlabcentr…exchange/21579>
The Matlab Grib-Reader requires CDI libraries from here: <https://code.zmaw.de/projects/cdi/files>
The libraries must be compiled with the own machine, i used this terminal commands:
./configure CFLAGS=-fPIC CPPFLAGS=-fPIC –enable-shared
make
I copied the resulting libcdi.a library into the lib64 folder, and executed compile.m which gave me the following:
COMPILING cdi_varlist…
cdi_mx.c: In function ‘getLevel’:
cdi_mx.c:431: warning: incompatible implicit declaration of built-in function ‘modf’
Undefined symbols for architecture x86_64:
"_Warning", referenced from:
_getLevel in cdi_mx.o
(maybe you meant: _Warning_)
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
mex: link of ‘ "cdi_varlist.mexmaci64"’ failed.
Error using mex (line 206)
Unable to complete successfully.
Error in compile (line 15)
mex cdi_varlist.c cdi_mx.c -Iinclude -Llib64 -lcdi -lnetcdf
Who can help?
PS: Matlab 2012a, Mac OS X 10.8.2, Xcode 4.6 grib compile mex MATLAB Answers — New Questions
Problems Reading GRiB files with NCTOOLBOX
Greetings,
I use MATLAB 2013a on a Windows 7 platform and am having trouble reading GRiB files with the NCTOOLBOX package (downloaded from https://github.com/nctoolbox/nctoolbox). The package reads netcdf fine….but gives a whole slew of errors for GRiB (yes I verified the GRiB was good).
My question is……is anyone having trouble reading GRiB on Windows platforms? If not, what are you using to read the data?Greetings,
I use MATLAB 2013a on a Windows 7 platform and am having trouble reading GRiB files with the NCTOOLBOX package (downloaded from https://github.com/nctoolbox/nctoolbox). The package reads netcdf fine….but gives a whole slew of errors for GRiB (yes I verified the GRiB was good).
My question is……is anyone having trouble reading GRiB on Windows platforms? If not, what are you using to read the data? Greetings,
I use MATLAB 2013a on a Windows 7 platform and am having trouble reading GRiB files with the NCTOOLBOX package (downloaded from https://github.com/nctoolbox/nctoolbox). The package reads netcdf fine….but gives a whole slew of errors for GRiB (yes I verified the GRiB was good).
My question is……is anyone having trouble reading GRiB on Windows platforms? If not, what are you using to read the data? read grib, windows MATLAB Answers — New Questions
what the logarithm of 85.64/5.946
please can youanswer te quesustionplease can youanswer te quesustion please can youanswer te quesustion please answer MATLAB Answers — New Questions
Problems with reward generation in reinforcement learning simulation
Hi everyone,
I am currently running a reinforcement learning model, integrated with simevents blocks in simulink. I have both a reinforcement learning script and the RL agent present in the simulink. Currently my reward function works based on a matlab function block that is connected to the reward input of RL agent block. I am facing an issue of constant reward generated throughout the entire episodes of RL iteration. Any ideas why? Because I try to assign the reward function (code below) as simple as possible, extract values from the entities of simevents, to generate values that are supposed to be different with each iteration.
function r = w(u1, u2, u3) %#codegen
% Extract Entities
FH = u1 + 1;
Cost = u2 + 1;
Downtime = u3 + 1;
% Reward calculation based on values
r = (Downtime/Cost) * FH;
end
There seems to be a problem as well because this reward area is red, eventhough the simulation runs normally.
I uploaded my model and a screenshot of the RL training result of the reward. If you are interested to replicate my results here are the steps:
Run script A.mlx to generate random number set A
Run script B.mlx to generate random number set B
Run MainScript.mlx to run the simulation
Thank you so much in advance! Let me know should you require any further information.
Best,
Aaron.Hi everyone,
I am currently running a reinforcement learning model, integrated with simevents blocks in simulink. I have both a reinforcement learning script and the RL agent present in the simulink. Currently my reward function works based on a matlab function block that is connected to the reward input of RL agent block. I am facing an issue of constant reward generated throughout the entire episodes of RL iteration. Any ideas why? Because I try to assign the reward function (code below) as simple as possible, extract values from the entities of simevents, to generate values that are supposed to be different with each iteration.
function r = w(u1, u2, u3) %#codegen
% Extract Entities
FH = u1 + 1;
Cost = u2 + 1;
Downtime = u3 + 1;
% Reward calculation based on values
r = (Downtime/Cost) * FH;
end
There seems to be a problem as well because this reward area is red, eventhough the simulation runs normally.
I uploaded my model and a screenshot of the RL training result of the reward. If you are interested to replicate my results here are the steps:
Run script A.mlx to generate random number set A
Run script B.mlx to generate random number set B
Run MainScript.mlx to run the simulation
Thank you so much in advance! Let me know should you require any further information.
Best,
Aaron. Hi everyone,
I am currently running a reinforcement learning model, integrated with simevents blocks in simulink. I have both a reinforcement learning script and the RL agent present in the simulink. Currently my reward function works based on a matlab function block that is connected to the reward input of RL agent block. I am facing an issue of constant reward generated throughout the entire episodes of RL iteration. Any ideas why? Because I try to assign the reward function (code below) as simple as possible, extract values from the entities of simevents, to generate values that are supposed to be different with each iteration.
function r = w(u1, u2, u3) %#codegen
% Extract Entities
FH = u1 + 1;
Cost = u2 + 1;
Downtime = u3 + 1;
% Reward calculation based on values
r = (Downtime/Cost) * FH;
end
There seems to be a problem as well because this reward area is red, eventhough the simulation runs normally.
I uploaded my model and a screenshot of the RL training result of the reward. If you are interested to replicate my results here are the steps:
Run script A.mlx to generate random number set A
Run script B.mlx to generate random number set B
Run MainScript.mlx to run the simulation
Thank you so much in advance! Let me know should you require any further information.
Best,
Aaron. matlab, simulink, matlab function MATLAB Answers — New Questions
How to create a initialize function for a custom layer where the learnable parameters have same size of input?
I want to form a initialize function inside a custom layer where the learnable parameters have same size as the unknown input size. Is it possible? I understood from Define Custom Deep Learning Layer with Learnable Parameters – MATLAB & Simulink – MathWorks India that this can be acquired by utilizing networkDataLayout objects. For instance while creating the deep learning network matlab will analyze the network by using input having a batch size ‘1’ and later on training it will change based on the batch size that we provide in the training options. Is there any way to initialize the custom layer in that way?I want to form a initialize function inside a custom layer where the learnable parameters have same size as the unknown input size. Is it possible? I understood from Define Custom Deep Learning Layer with Learnable Parameters – MATLAB & Simulink – MathWorks India that this can be acquired by utilizing networkDataLayout objects. For instance while creating the deep learning network matlab will analyze the network by using input having a batch size ‘1’ and later on training it will change based on the batch size that we provide in the training options. Is there any way to initialize the custom layer in that way? I want to form a initialize function inside a custom layer where the learnable parameters have same size as the unknown input size. Is it possible? I understood from Define Custom Deep Learning Layer with Learnable Parameters – MATLAB & Simulink – MathWorks India that this can be acquired by utilizing networkDataLayout objects. For instance while creating the deep learning network matlab will analyze the network by using input having a batch size ‘1’ and later on training it will change based on the batch size that we provide in the training options. Is there any way to initialize the custom layer in that way? signal processing, digital signal processing, image processing, digital image processing, deep learning, machine learning, matlab, matlab gui, matrix manipulation, matrix MATLAB Answers — New Questions
moving median with variable window
Is there any way how to effectively generalize movmedian function to work with variable window length or local variable k-point median values, where k is vector with the same length as length of input vector (lenght(x) = lenght(k))?
Example:
x = 1:6
k = 2,3,3,5,3,2
M = movmedian_vk(x,k)
M = 1, 2, 3, 4, 5, 5.5
My naive solution looks like:
function M = movmedian_vk(x,k)
if length(k) ~= length(x)
error(‘Incomaptible input data’)
end
M = zeros(size(x));
[uk,~,ck] = unique(k);
for i = 1:length(uk)
M_i = movmedian(x,uk(i));
I_i = (ck == i);
M(I_i) = M_i(I_i);
end
endIs there any way how to effectively generalize movmedian function to work with variable window length or local variable k-point median values, where k is vector with the same length as length of input vector (lenght(x) = lenght(k))?
Example:
x = 1:6
k = 2,3,3,5,3,2
M = movmedian_vk(x,k)
M = 1, 2, 3, 4, 5, 5.5
My naive solution looks like:
function M = movmedian_vk(x,k)
if length(k) ~= length(x)
error(‘Incomaptible input data’)
end
M = zeros(size(x));
[uk,~,ck] = unique(k);
for i = 1:length(uk)
M_i = movmedian(x,uk(i));
I_i = (ck == i);
M(I_i) = M_i(I_i);
end
end Is there any way how to effectively generalize movmedian function to work with variable window length or local variable k-point median values, where k is vector with the same length as length of input vector (lenght(x) = lenght(k))?
Example:
x = 1:6
k = 2,3,3,5,3,2
M = movmedian_vk(x,k)
M = 1, 2, 3, 4, 5, 5.5
My naive solution looks like:
function M = movmedian_vk(x,k)
if length(k) ~= length(x)
error(‘Incomaptible input data’)
end
M = zeros(size(x));
[uk,~,ck] = unique(k);
for i = 1:length(uk)
M_i = movmedian(x,uk(i));
I_i = (ck == i);
M(I_i) = M_i(I_i);
end
end moving, median MATLAB Answers — New Questions
Simulink Desktop Real-Time Kernel error: Maximum supported number of timers exceeded?
Hi all,
I’m using the Simulink Desktop Real-Time toolbox in MATLAB 2024a Update 6.
I’m on Windows 10 with Hyper-V and High Precision Event Timer enabled.
I’m reading and writing quite a lot (100+) of CAN and CAN-FD frames using the Packet Input and Packet Output blocks.
I’m using both the ‘Connected IO’ and ‘Run in Kernel’ modes depending on my needs: ‘Connected IO’ allows more interactivity whereas ‘Run in Kernel’ guarantees real-time performance.
I used to use CAN FD Receive and CAN FD Transmit blocks from the Vehicle Network toolbox, which I prefered because they allowed me to receive and send multiple CAN(FD) frames with a single block. But unfortunately they’re not compatible with the ‘Run in Kernel’ mode (see this answer).
My issue is that I have so many Packet Input and Packet Output blocks, that I get this error in ‘Connected IO’ mode :
Error reported by S-function ‘sldrtsync’:
Maximum supported number of timers exceeded.
What is the maximum number of timers allowed?
Is there a way to increase this number (in the toolbox options maybe?), or is it hard-coded in the real-time kernel?
What would be the alternatives to send/receive many CAN(FD) frames in ‘Connected IO’ mode ?
Thank youHi all,
I’m using the Simulink Desktop Real-Time toolbox in MATLAB 2024a Update 6.
I’m on Windows 10 with Hyper-V and High Precision Event Timer enabled.
I’m reading and writing quite a lot (100+) of CAN and CAN-FD frames using the Packet Input and Packet Output blocks.
I’m using both the ‘Connected IO’ and ‘Run in Kernel’ modes depending on my needs: ‘Connected IO’ allows more interactivity whereas ‘Run in Kernel’ guarantees real-time performance.
I used to use CAN FD Receive and CAN FD Transmit blocks from the Vehicle Network toolbox, which I prefered because they allowed me to receive and send multiple CAN(FD) frames with a single block. But unfortunately they’re not compatible with the ‘Run in Kernel’ mode (see this answer).
My issue is that I have so many Packet Input and Packet Output blocks, that I get this error in ‘Connected IO’ mode :
Error reported by S-function ‘sldrtsync’:
Maximum supported number of timers exceeded.
What is the maximum number of timers allowed?
Is there a way to increase this number (in the toolbox options maybe?), or is it hard-coded in the real-time kernel?
What would be the alternatives to send/receive many CAN(FD) frames in ‘Connected IO’ mode ?
Thank you Hi all,
I’m using the Simulink Desktop Real-Time toolbox in MATLAB 2024a Update 6.
I’m on Windows 10 with Hyper-V and High Precision Event Timer enabled.
I’m reading and writing quite a lot (100+) of CAN and CAN-FD frames using the Packet Input and Packet Output blocks.
I’m using both the ‘Connected IO’ and ‘Run in Kernel’ modes depending on my needs: ‘Connected IO’ allows more interactivity whereas ‘Run in Kernel’ guarantees real-time performance.
I used to use CAN FD Receive and CAN FD Transmit blocks from the Vehicle Network toolbox, which I prefered because they allowed me to receive and send multiple CAN(FD) frames with a single block. But unfortunately they’re not compatible with the ‘Run in Kernel’ mode (see this answer).
My issue is that I have so many Packet Input and Packet Output blocks, that I get this error in ‘Connected IO’ mode :
Error reported by S-function ‘sldrtsync’:
Maximum supported number of timers exceeded.
What is the maximum number of timers allowed?
Is there a way to increase this number (in the toolbox options maybe?), or is it hard-coded in the real-time kernel?
What would be the alternatives to send/receive many CAN(FD) frames in ‘Connected IO’ mode ?
Thank you can, sldrt MATLAB Answers — New Questions