Category: Matlab
Category Archives: Matlab
Is the Trust-Region-Reflective algorithm the same for minimizing a scalar function and solving a nonlinear system of equations?
I’m tring to solve a system of "blackbox" residual function (F(x)=0) and was wondering if it is better to solve the system or to minimize the sum of the equations as a single scalar function.
It seems the same if the system is solved as a least square problem using lsqnonlin, especially when looking to the available algorithms, like the Trust-Region.
Is the Trust-Region algorithm the same for minimizing a scalar function and solving a nonlinear system of equations?I’m tring to solve a system of "blackbox" residual function (F(x)=0) and was wondering if it is better to solve the system or to minimize the sum of the equations as a single scalar function.
It seems the same if the system is solved as a least square problem using lsqnonlin, especially when looking to the available algorithms, like the Trust-Region.
Is the Trust-Region algorithm the same for minimizing a scalar function and solving a nonlinear system of equations? I’m tring to solve a system of "blackbox" residual function (F(x)=0) and was wondering if it is better to solve the system or to minimize the sum of the equations as a single scalar function.
It seems the same if the system is solved as a least square problem using lsqnonlin, especially when looking to the available algorithms, like the Trust-Region.
Is the Trust-Region algorithm the same for minimizing a scalar function and solving a nonlinear system of equations? lsqnonlin, optimization, fmincon MATLAB Answers — New Questions
Can I send image from Matlab to iPhone?
Hi,I’m developing iOS app. then,I need the results from Matlab and show it on application. Are there any solutions of Matlab for sending the image to iPhone. Could someone help me an example or recommendations ? I would be really appreciated. Thank you so much:)Hi,I’m developing iOS app. then,I need the results from Matlab and show it on application. Are there any solutions of Matlab for sending the image to iPhone. Could someone help me an example or recommendations ? I would be really appreciated. Thank you so much:) Hi,I’m developing iOS app. then,I need the results from Matlab and show it on application. Are there any solutions of Matlab for sending the image to iPhone. Could someone help me an example or recommendations ? I would be really appreciated. Thank you so much:) communication, iphone MATLAB Answers — New Questions
How to define a slicing like x(i).property in a custom class?
One minor but useful thing about image feature classes in MATLAB is that they have varieties of ways to slice the feature points and get a subset. For example, let’s say we extract SIFT features from an image:
I = imread(‘cameraman.tif’);
points = detectSIFTFeatures(I);
fprintf(‘Number of detected points: %dn’, points.Count);
We have the following ways to slice them, which give us the same sets of results:
% Subset of indices
subs = 1:10;
% Method 1
a = points(subs);
aa = a.Location;
% Method 2
b = points.Location;
bb = b(subs,:);
% Method 3
c = points.Location(subs,:);
% Method 4
d = points(subs).Location;
I’m wondering how to define a custom class to achieve all these slicing methods. I tried to use subsref function to define a custom class like this:
% File name: MyCustomPoints.m
classdef MyCustomPoints
properties
Scale % (n x 1)
Location % (n x 2)
end
methods (Access=’public’)
% Constructor
function this = MyCustomPoints(scale, location)
this.Scale = scale;
this.Location = location;
end
% Slicing
function varargout = subsref(this, s)
switch s(1).type
case ‘()’
subs = s(1).subs{1};
varargout{1} = MyCustomPoints(this.Scale(subs,:), …
this.Location(subs,:));
case ‘.’
% Handle property access
if isscalar(s)
varargout{1} = this.(s(1).subs);
else
[varargout{1:nargout}] = builtin(‘subsref’, this, s);
end
end
end
end
end
Below is an example usage of this class:
% Example input
Scale = rand(100,1);
Location = rand(100,2);
myPoints = MyCustomPoints(Scale, Location);
subs = 1:3; % subset indices
% Method 1
a = myPoints(subs);
aa = a.Location; % –> Successful.
% Method 2
b = myPoints.Location;
bb = b(subs,:); % –> Successful.
% Method 3
c = myPoints.Location(subs,:); % –> Successful.
% Method 4
d = myPoints(subs).Location; % –> Failed.
Only the last slicing method gives me an error message:
Output argument "varargout{2}" (and possibly others) not assigned a value
in the execution with "MyCustomPoints/subsref" function.
Could you please advise how to modify my class to enable all the slicing methods above?One minor but useful thing about image feature classes in MATLAB is that they have varieties of ways to slice the feature points and get a subset. For example, let’s say we extract SIFT features from an image:
I = imread(‘cameraman.tif’);
points = detectSIFTFeatures(I);
fprintf(‘Number of detected points: %dn’, points.Count);
We have the following ways to slice them, which give us the same sets of results:
% Subset of indices
subs = 1:10;
% Method 1
a = points(subs);
aa = a.Location;
% Method 2
b = points.Location;
bb = b(subs,:);
% Method 3
c = points.Location(subs,:);
% Method 4
d = points(subs).Location;
I’m wondering how to define a custom class to achieve all these slicing methods. I tried to use subsref function to define a custom class like this:
% File name: MyCustomPoints.m
classdef MyCustomPoints
properties
Scale % (n x 1)
Location % (n x 2)
end
methods (Access=’public’)
% Constructor
function this = MyCustomPoints(scale, location)
this.Scale = scale;
this.Location = location;
end
% Slicing
function varargout = subsref(this, s)
switch s(1).type
case ‘()’
subs = s(1).subs{1};
varargout{1} = MyCustomPoints(this.Scale(subs,:), …
this.Location(subs,:));
case ‘.’
% Handle property access
if isscalar(s)
varargout{1} = this.(s(1).subs);
else
[varargout{1:nargout}] = builtin(‘subsref’, this, s);
end
end
end
end
end
Below is an example usage of this class:
% Example input
Scale = rand(100,1);
Location = rand(100,2);
myPoints = MyCustomPoints(Scale, Location);
subs = 1:3; % subset indices
% Method 1
a = myPoints(subs);
aa = a.Location; % –> Successful.
% Method 2
b = myPoints.Location;
bb = b(subs,:); % –> Successful.
% Method 3
c = myPoints.Location(subs,:); % –> Successful.
% Method 4
d = myPoints(subs).Location; % –> Failed.
Only the last slicing method gives me an error message:
Output argument "varargout{2}" (and possibly others) not assigned a value
in the execution with "MyCustomPoints/subsref" function.
Could you please advise how to modify my class to enable all the slicing methods above? One minor but useful thing about image feature classes in MATLAB is that they have varieties of ways to slice the feature points and get a subset. For example, let’s say we extract SIFT features from an image:
I = imread(‘cameraman.tif’);
points = detectSIFTFeatures(I);
fprintf(‘Number of detected points: %dn’, points.Count);
We have the following ways to slice them, which give us the same sets of results:
% Subset of indices
subs = 1:10;
% Method 1
a = points(subs);
aa = a.Location;
% Method 2
b = points.Location;
bb = b(subs,:);
% Method 3
c = points.Location(subs,:);
% Method 4
d = points(subs).Location;
I’m wondering how to define a custom class to achieve all these slicing methods. I tried to use subsref function to define a custom class like this:
% File name: MyCustomPoints.m
classdef MyCustomPoints
properties
Scale % (n x 1)
Location % (n x 2)
end
methods (Access=’public’)
% Constructor
function this = MyCustomPoints(scale, location)
this.Scale = scale;
this.Location = location;
end
% Slicing
function varargout = subsref(this, s)
switch s(1).type
case ‘()’
subs = s(1).subs{1};
varargout{1} = MyCustomPoints(this.Scale(subs,:), …
this.Location(subs,:));
case ‘.’
% Handle property access
if isscalar(s)
varargout{1} = this.(s(1).subs);
else
[varargout{1:nargout}] = builtin(‘subsref’, this, s);
end
end
end
end
end
Below is an example usage of this class:
% Example input
Scale = rand(100,1);
Location = rand(100,2);
myPoints = MyCustomPoints(Scale, Location);
subs = 1:3; % subset indices
% Method 1
a = myPoints(subs);
aa = a.Location; % –> Successful.
% Method 2
b = myPoints.Location;
bb = b(subs,:); % –> Successful.
% Method 3
c = myPoints.Location(subs,:); % –> Successful.
% Method 4
d = myPoints(subs).Location; % –> Failed.
Only the last slicing method gives me an error message:
Output argument "varargout{2}" (and possibly others) not assigned a value
in the execution with "MyCustomPoints/subsref" function.
Could you please advise how to modify my class to enable all the slicing methods above? class, slicing, structures MATLAB Answers — New Questions
Name a dataset that will be used in Simulink
How do I name a dataset. My dataset is available in Simulink; however, it is identified as unnamed. I want to use multiple datasets so I need to be able to identify each of them separately.
clc
% Parameters
f0 = 60; % Fundamental frequency in Hz
sampling_rate = 120000; % Sampling rate in Hz
stopTime = 0.1; % Duration of the signal in seconds
t = 0:1/sampling_rate:stopTime; % Time vector
% Harmonic amplitudes (example values)
IA = [771.32, 0.24,1.36, 0.96, 6.64, 0.16, 2.36, 0, 0.48,…
0.16, 1.84, 0.08, 0.56, 0.08, 0.32, 0.08, 0.24,…
0.08, 0.08, 0.08, 0.08, 0, 0.48, 0, 0.16, 0.08, 0.08, 0, 0.08, 0, 0, 0, 0,…
0.08, 0.24, 0.16, 0.32, 0.08, 0.08, 0.08, 0.32,…
0.08, 0.24, 0.16, 0.24, 0.08, 0.8, 0.16, 0.48,…
0.16, 0.16, 0.08, 0.72, 0.24, 0.72, 0.16, 0.24,…
0.08, 0.16, 0.08, 0.56, 0.08, 0.32]’; % Amplitudes for the 1st, 2nd, and 3rd harmonics
IB = [773.44, 0.4, 0.72, 0.88, 6.16, 0.4, 2.84, 0.08, 0.4, 0.08,…
1.76, 0.08, 0.96, 0.08, 0.16, 0, 0.4, 0.08, …
0.24, 0.08, 0, 0, 0.4, 0, 0.24, 0,…
0.08, 0, 0.08, 0, 0.08, 0, 0.16, 0.08,…
0.16, 0.08, 0.32, 0.08, 0.08, 0, 0.24, 0.08,…
0.4, 0.08, 0.08, 0.08, 0.8, 0.08, 0.72, 0.16,…
0.08, 0.32, 0.48, 0, 0.08, 0.08, 0.24, 0.32,…
0.24, 0.24, 0.72, 0.24, 0.08];
IC = [775.76, 0.24, 0.56, 0.72, 6.48, 0.24, 2.44, 0.08, 0.08, 0.08, …
2.12, 0, 0.72, 0.08, 0.16, 0.08,…
0.32, 0, 0.08, 0, 0, 0, 0.56, 0, 0.08, 0, 0.08, 0, …
0, 0, 0.08, 0, 0, 0, 0.24, 0, 0.24, 0, 0, 0.08, 0.24, 0, 0.32, 0,…
0.08, 0.08, 0.8, 0.08, 0.56, 0.08, 0.32, 0.08,…
0.64, 0.32, 0.56, 0.08, 0.24, 0.32, 0.24, 0.32, 0.72, 0.16, 0.24];
%% Generate the current
currentIA = zeros(size(t));
currentIB = zeros(size(t));
currentIC = zeros(size(t));
for n = 1:length(IA)
amplitudeIA = IA(n);
currentIA = currentIA + amplitudeIA * cos(2 * pi * n * f0 * t);
amplitudeIB = IB(n);
currentIB = currentIB + amplitudeIB * cos(2 * pi * n * f0 * t + 2*pi/3);
amplitudeIC = IC(n);
currentIC = currentIC + amplitudeIC * cos(2 * pi * n * f0 * t – 2*pi/3);
end
currents = timeseries([currentIA; currentIB; currentIC]’, t);
dataset = Simulink.SimulationData.Dataset(currents); %How do I give the dataset a name?
save currentsWith63Harmonics.mat dataset
%% Plot the signal
figure(1);
plot(t, currentIA);
hold on
plot(t, currentIB);
plot(t, currentIC);
title(‘Three-Phase currents with 63 harmonics’);
xlabel(‘Time (s)’);
ylabel(‘A’);
grid on;
figure(2);
ee_calculateThdPercent(1:1:63,IA’)
bar(1:1:63,IA’)
clear IA IB IC f0 duration amplitudeIA amplitudeIB amplitudeIC
clear n t signalHow do I name a dataset. My dataset is available in Simulink; however, it is identified as unnamed. I want to use multiple datasets so I need to be able to identify each of them separately.
clc
% Parameters
f0 = 60; % Fundamental frequency in Hz
sampling_rate = 120000; % Sampling rate in Hz
stopTime = 0.1; % Duration of the signal in seconds
t = 0:1/sampling_rate:stopTime; % Time vector
% Harmonic amplitudes (example values)
IA = [771.32, 0.24,1.36, 0.96, 6.64, 0.16, 2.36, 0, 0.48,…
0.16, 1.84, 0.08, 0.56, 0.08, 0.32, 0.08, 0.24,…
0.08, 0.08, 0.08, 0.08, 0, 0.48, 0, 0.16, 0.08, 0.08, 0, 0.08, 0, 0, 0, 0,…
0.08, 0.24, 0.16, 0.32, 0.08, 0.08, 0.08, 0.32,…
0.08, 0.24, 0.16, 0.24, 0.08, 0.8, 0.16, 0.48,…
0.16, 0.16, 0.08, 0.72, 0.24, 0.72, 0.16, 0.24,…
0.08, 0.16, 0.08, 0.56, 0.08, 0.32]’; % Amplitudes for the 1st, 2nd, and 3rd harmonics
IB = [773.44, 0.4, 0.72, 0.88, 6.16, 0.4, 2.84, 0.08, 0.4, 0.08,…
1.76, 0.08, 0.96, 0.08, 0.16, 0, 0.4, 0.08, …
0.24, 0.08, 0, 0, 0.4, 0, 0.24, 0,…
0.08, 0, 0.08, 0, 0.08, 0, 0.16, 0.08,…
0.16, 0.08, 0.32, 0.08, 0.08, 0, 0.24, 0.08,…
0.4, 0.08, 0.08, 0.08, 0.8, 0.08, 0.72, 0.16,…
0.08, 0.32, 0.48, 0, 0.08, 0.08, 0.24, 0.32,…
0.24, 0.24, 0.72, 0.24, 0.08];
IC = [775.76, 0.24, 0.56, 0.72, 6.48, 0.24, 2.44, 0.08, 0.08, 0.08, …
2.12, 0, 0.72, 0.08, 0.16, 0.08,…
0.32, 0, 0.08, 0, 0, 0, 0.56, 0, 0.08, 0, 0.08, 0, …
0, 0, 0.08, 0, 0, 0, 0.24, 0, 0.24, 0, 0, 0.08, 0.24, 0, 0.32, 0,…
0.08, 0.08, 0.8, 0.08, 0.56, 0.08, 0.32, 0.08,…
0.64, 0.32, 0.56, 0.08, 0.24, 0.32, 0.24, 0.32, 0.72, 0.16, 0.24];
%% Generate the current
currentIA = zeros(size(t));
currentIB = zeros(size(t));
currentIC = zeros(size(t));
for n = 1:length(IA)
amplitudeIA = IA(n);
currentIA = currentIA + amplitudeIA * cos(2 * pi * n * f0 * t);
amplitudeIB = IB(n);
currentIB = currentIB + amplitudeIB * cos(2 * pi * n * f0 * t + 2*pi/3);
amplitudeIC = IC(n);
currentIC = currentIC + amplitudeIC * cos(2 * pi * n * f0 * t – 2*pi/3);
end
currents = timeseries([currentIA; currentIB; currentIC]’, t);
dataset = Simulink.SimulationData.Dataset(currents); %How do I give the dataset a name?
save currentsWith63Harmonics.mat dataset
%% Plot the signal
figure(1);
plot(t, currentIA);
hold on
plot(t, currentIB);
plot(t, currentIC);
title(‘Three-Phase currents with 63 harmonics’);
xlabel(‘Time (s)’);
ylabel(‘A’);
grid on;
figure(2);
ee_calculateThdPercent(1:1:63,IA’)
bar(1:1:63,IA’)
clear IA IB IC f0 duration amplitudeIA amplitudeIB amplitudeIC
clear n t signal How do I name a dataset. My dataset is available in Simulink; however, it is identified as unnamed. I want to use multiple datasets so I need to be able to identify each of them separately.
clc
% Parameters
f0 = 60; % Fundamental frequency in Hz
sampling_rate = 120000; % Sampling rate in Hz
stopTime = 0.1; % Duration of the signal in seconds
t = 0:1/sampling_rate:stopTime; % Time vector
% Harmonic amplitudes (example values)
IA = [771.32, 0.24,1.36, 0.96, 6.64, 0.16, 2.36, 0, 0.48,…
0.16, 1.84, 0.08, 0.56, 0.08, 0.32, 0.08, 0.24,…
0.08, 0.08, 0.08, 0.08, 0, 0.48, 0, 0.16, 0.08, 0.08, 0, 0.08, 0, 0, 0, 0,…
0.08, 0.24, 0.16, 0.32, 0.08, 0.08, 0.08, 0.32,…
0.08, 0.24, 0.16, 0.24, 0.08, 0.8, 0.16, 0.48,…
0.16, 0.16, 0.08, 0.72, 0.24, 0.72, 0.16, 0.24,…
0.08, 0.16, 0.08, 0.56, 0.08, 0.32]’; % Amplitudes for the 1st, 2nd, and 3rd harmonics
IB = [773.44, 0.4, 0.72, 0.88, 6.16, 0.4, 2.84, 0.08, 0.4, 0.08,…
1.76, 0.08, 0.96, 0.08, 0.16, 0, 0.4, 0.08, …
0.24, 0.08, 0, 0, 0.4, 0, 0.24, 0,…
0.08, 0, 0.08, 0, 0.08, 0, 0.16, 0.08,…
0.16, 0.08, 0.32, 0.08, 0.08, 0, 0.24, 0.08,…
0.4, 0.08, 0.08, 0.08, 0.8, 0.08, 0.72, 0.16,…
0.08, 0.32, 0.48, 0, 0.08, 0.08, 0.24, 0.32,…
0.24, 0.24, 0.72, 0.24, 0.08];
IC = [775.76, 0.24, 0.56, 0.72, 6.48, 0.24, 2.44, 0.08, 0.08, 0.08, …
2.12, 0, 0.72, 0.08, 0.16, 0.08,…
0.32, 0, 0.08, 0, 0, 0, 0.56, 0, 0.08, 0, 0.08, 0, …
0, 0, 0.08, 0, 0, 0, 0.24, 0, 0.24, 0, 0, 0.08, 0.24, 0, 0.32, 0,…
0.08, 0.08, 0.8, 0.08, 0.56, 0.08, 0.32, 0.08,…
0.64, 0.32, 0.56, 0.08, 0.24, 0.32, 0.24, 0.32, 0.72, 0.16, 0.24];
%% Generate the current
currentIA = zeros(size(t));
currentIB = zeros(size(t));
currentIC = zeros(size(t));
for n = 1:length(IA)
amplitudeIA = IA(n);
currentIA = currentIA + amplitudeIA * cos(2 * pi * n * f0 * t);
amplitudeIB = IB(n);
currentIB = currentIB + amplitudeIB * cos(2 * pi * n * f0 * t + 2*pi/3);
amplitudeIC = IC(n);
currentIC = currentIC + amplitudeIC * cos(2 * pi * n * f0 * t – 2*pi/3);
end
currents = timeseries([currentIA; currentIB; currentIC]’, t);
dataset = Simulink.SimulationData.Dataset(currents); %How do I give the dataset a name?
save currentsWith63Harmonics.mat dataset
%% Plot the signal
figure(1);
plot(t, currentIA);
hold on
plot(t, currentIB);
plot(t, currentIC);
title(‘Three-Phase currents with 63 harmonics’);
xlabel(‘Time (s)’);
ylabel(‘A’);
grid on;
figure(2);
ee_calculateThdPercent(1:1:63,IA’)
bar(1:1:63,IA’)
clear IA IB IC f0 duration amplitudeIA amplitudeIB amplitudeIC
clear n t signal naming datasets in matlab MATLAB Answers — New Questions
How to resolve warning message about broadcast variable while using ‘parfor’?
males = {‘animal1’, ‘animal2’, ‘animal3’};
treatmentGrps = {‘T1’, ‘T2’, ‘T3’};
nrows = size(featureLists, 1);
ncols = size(featureLists, 2);
featureLists = cell(nrows, ncols);
parfor grp = 1:nrows
tempRow = cell(1, ncols);
for animal = 1:ncols
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
featureLists(grp, 🙂 = tempRow;
end
When I use ‘parfor’ like above I get an warning message
The entire array or structure ‘males’ is a broadcast variable.
This might result in unnecessary communication overhead.
But, when I change ‘ncols’ to ‘numel(males)’ like following
for animal = 1:numel(males)
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
for the inner loop I don’t get any warning.
Can someone please explain this behavior of ‘parfor’?males = {‘animal1’, ‘animal2’, ‘animal3’};
treatmentGrps = {‘T1’, ‘T2’, ‘T3’};
nrows = size(featureLists, 1);
ncols = size(featureLists, 2);
featureLists = cell(nrows, ncols);
parfor grp = 1:nrows
tempRow = cell(1, ncols);
for animal = 1:ncols
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
featureLists(grp, 🙂 = tempRow;
end
When I use ‘parfor’ like above I get an warning message
The entire array or structure ‘males’ is a broadcast variable.
This might result in unnecessary communication overhead.
But, when I change ‘ncols’ to ‘numel(males)’ like following
for animal = 1:numel(males)
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
for the inner loop I don’t get any warning.
Can someone please explain this behavior of ‘parfor’? males = {‘animal1’, ‘animal2’, ‘animal3’};
treatmentGrps = {‘T1’, ‘T2’, ‘T3’};
nrows = size(featureLists, 1);
ncols = size(featureLists, 2);
featureLists = cell(nrows, ncols);
parfor grp = 1:nrows
tempRow = cell(1, ncols);
for animal = 1:ncols
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
featureLists(grp, 🙂 = tempRow;
end
When I use ‘parfor’ like above I get an warning message
The entire array or structure ‘males’ is a broadcast variable.
This might result in unnecessary communication overhead.
But, when I change ‘ncols’ to ‘numel(males)’ like following
for animal = 1:numel(males)
tempRow{animal} = individualPsychValuesPerSession(‘approachavoid’, …
treatmentGrps{grp}, males{animal});
end
for the inner loop I don’t get any warning.
Can someone please explain this behavior of ‘parfor’? parfor, matlab MATLAB Answers — New Questions
How to get warning source
Good day everyone,
I have a very long matlab code, and I get the folowing warning when runing (about as much as matlab can spill out into the console per second):
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
How do I get the file / line number generating this warning?
Thank you very much.Good day everyone,
I have a very long matlab code, and I get the folowing warning when runing (about as much as matlab can spill out into the console per second):
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
How do I get the file / line number generating this warning?
Thank you very much. Good day everyone,
I have a very long matlab code, and I get the folowing warning when runing (about as much as matlab can spill out into the console per second):
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
How do I get the file / line number generating this warning?
Thank you very much. warning MATLAB Answers — New Questions
Load flow doesn’t run properly, the results in all buses are 0
Hi everyone,
I am triying to obtain the load flow buses results in the load flow analyzer table but it only appears "0". Moreover, it sends an error message telling that there is no swing bus but I have a 3 phase programmable voltage source in my model. I attach an image with my simulation model.
Thank you!Hi everyone,
I am triying to obtain the load flow buses results in the load flow analyzer table but it only appears "0". Moreover, it sends an error message telling that there is no swing bus but I have a 3 phase programmable voltage source in my model. I attach an image with my simulation model.
Thank you! Hi everyone,
I am triying to obtain the load flow buses results in the load flow analyzer table but it only appears "0". Moreover, it sends an error message telling that there is no swing bus but I have a 3 phase programmable voltage source in my model. I attach an image with my simulation model.
Thank you! load flow MATLAB Answers — New Questions
plot(skin friction)
skinfriction()
function skinfriction
Nt=0.5; Nb=0.5; Le=2; Pr=1; alpha=1.5; s=1; A=3;
%% solution in structure form
%First solution
sol = bvpinit(linspace(0,6,10), [0 0 0 0 0 0 0]);
sol1 = bvp4c(@bvpexam2, @bcexam2, sol);
x1 = sol1.x;
y1 = sol1.y;
% Second solution
opts = bvpset(‘stats’,’off’,’RelTol’,1e-10);
sol = bvpinit(linspace(0,5,10), [-1 0 0 0 0 0 0]);
sol2 = bvp4c(@bvpexam2, @bcexam2_dual, sol,opts);
x2 = sol2.x;
y2 = sol2.y;
% Plot both solutions
plot(x1,y1(3,:),’-‘); hold on
plot(x2,y2(3,:),’–‘);
xlabel(‘eta’)
ylabel(‘f`(eta)’)
result1 = A^(-1/2)*y1(3,1)
result2 = A^(-1/2)*y2(3,1)
%%residual of bcs
function res = bcexam2(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
function res = bcexam2_dual(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
%% first order odes
function ysol = bvpexam2(x,y)
yy1 = -(A*y(1)*y(3)-A*(y(2))^2)-y(2)-(x/2)*y(3);
yy2 = -Pr*(A*y(1)*y(5)+(x/2)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2);
yy3 = (-Le*(A*(y(1)*y(7)+(x/2)*y(7)))-(Nt/Nb)*( -Pr*(A*y(1)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2)));
ysol = [y(2); y(3); yy1;y(5);yy2;y(7);yy3];
end
end
please help to plot this graph using the above codeskinfriction()
function skinfriction
Nt=0.5; Nb=0.5; Le=2; Pr=1; alpha=1.5; s=1; A=3;
%% solution in structure form
%First solution
sol = bvpinit(linspace(0,6,10), [0 0 0 0 0 0 0]);
sol1 = bvp4c(@bvpexam2, @bcexam2, sol);
x1 = sol1.x;
y1 = sol1.y;
% Second solution
opts = bvpset(‘stats’,’off’,’RelTol’,1e-10);
sol = bvpinit(linspace(0,5,10), [-1 0 0 0 0 0 0]);
sol2 = bvp4c(@bvpexam2, @bcexam2_dual, sol,opts);
x2 = sol2.x;
y2 = sol2.y;
% Plot both solutions
plot(x1,y1(3,:),’-‘); hold on
plot(x2,y2(3,:),’–‘);
xlabel(‘eta’)
ylabel(‘f`(eta)’)
result1 = A^(-1/2)*y1(3,1)
result2 = A^(-1/2)*y2(3,1)
%%residual of bcs
function res = bcexam2(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
function res = bcexam2_dual(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
%% first order odes
function ysol = bvpexam2(x,y)
yy1 = -(A*y(1)*y(3)-A*(y(2))^2)-y(2)-(x/2)*y(3);
yy2 = -Pr*(A*y(1)*y(5)+(x/2)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2);
yy3 = (-Le*(A*(y(1)*y(7)+(x/2)*y(7)))-(Nt/Nb)*( -Pr*(A*y(1)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2)));
ysol = [y(2); y(3); yy1;y(5);yy2;y(7);yy3];
end
end
please help to plot this graph using the above code skinfriction()
function skinfriction
Nt=0.5; Nb=0.5; Le=2; Pr=1; alpha=1.5; s=1; A=3;
%% solution in structure form
%First solution
sol = bvpinit(linspace(0,6,10), [0 0 0 0 0 0 0]);
sol1 = bvp4c(@bvpexam2, @bcexam2, sol);
x1 = sol1.x;
y1 = sol1.y;
% Second solution
opts = bvpset(‘stats’,’off’,’RelTol’,1e-10);
sol = bvpinit(linspace(0,5,10), [-1 0 0 0 0 0 0]);
sol2 = bvp4c(@bvpexam2, @bcexam2_dual, sol,opts);
x2 = sol2.x;
y2 = sol2.y;
% Plot both solutions
plot(x1,y1(3,:),’-‘); hold on
plot(x2,y2(3,:),’–‘);
xlabel(‘eta’)
ylabel(‘f`(eta)’)
result1 = A^(-1/2)*y1(3,1)
result2 = A^(-1/2)*y2(3,1)
%%residual of bcs
function res = bcexam2(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
function res = bcexam2_dual(y0, yinf)
res= [y0(1)-s; y0(2)-alpha; y0(4)-1; y0(6)-1; yinf(2); yinf(4);yinf(6)];
end
%% first order odes
function ysol = bvpexam2(x,y)
yy1 = -(A*y(1)*y(3)-A*(y(2))^2)-y(2)-(x/2)*y(3);
yy2 = -Pr*(A*y(1)*y(5)+(x/2)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2);
yy3 = (-Le*(A*(y(1)*y(7)+(x/2)*y(7)))-(Nt/Nb)*( -Pr*(A*y(1)*y(5)+Nb*y(5)*y(7)+Nt*(y(5))^2)));
ysol = [y(2); y(3); yy1;y(5);yy2;y(7);yy3];
end
end
please help to plot this graph using the above code matlab MATLAB Answers — New Questions
Who explain me this code ?
% Section 1 : Chargement des noms de fichiers et dates
filenames = dir; % Récupère la liste des fichiers dans le répertoire courant
clear files dates % Efface les variables ‘files’ et ‘dates’ si elles existent
for i = 3:size(filenames, 1) % Boucle à partir du troisième élément pour ignorer ‘.’ et ‘..’
files{i-2} = filenames(i).name; % Stocke le nom du fichier dans ‘files’
dates{i-2} = filenames(i).date; % Stocke la date du fichier dans ‘dates’
end
% Section 2 : Chargement des images
clear I % Efface la variable ‘I’ si elle existe
ii = 1; % Initialise l’index pour les images chargées
for i = 1:size(files, 2) % Boucle sur tous les fichiers
try
I{ii} = imread(files{i}); % Tente de lire l’image et la stocke dans ‘I’
ii = ii + 1; % Incrémente l’index
catch
i % Affiche l’index de l’image qui ne peut pas être lue
end
end
% Section 3 : Extraction des visages
for i = 1:29 % Boucle sur les 29 premières images
Face(:, :, i) = extractFace(I{i}); % Extrait le visage de l’image et le stocke dans ‘Face’
end
for i = 1:29 % Boucle pour afficher les visages extraits
figure
image(Face(:, :, i)); colormap(gray); % Affiche le visage en niveaux de gris
end
% Section 4 : Conversion des images en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
imagesc(X) % Affiche la matrice ‘X’ sous forme d’image
% Section 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
imagesc(reshape(averageFace, [100 100])); colormap(gray); % Affiche le visage moyen
% Section 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Section 7 : Décomposition en valeurs singulières (SVD)
[U, S, D] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Section 8 : Affichage des valeurs singulières
diag(S) % Affiche les valeurs singulières sous forme de vecteur diagonal
% Section 9 : Affichage des Eigenfaces
for i = 1:9 % Boucle pour afficher les 9 premiers eigenfaces
figure
imagesc(reshape(U(:, i), [100 100])); % Affiche chaque eigenface
colormap(gray);
end
% Section 10 : Reconnaissance de visage
RegFace = X(:, 9); % Sélectionne un visage de référence dans ‘X’
imagesc(reshape(RegFace, [100 100])); colormap(gray); axis image; % Affiche le visage de référence
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage de référence dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage à partir de l’espace des visages
imagesc(reshape(HFace, [100 100])); colormap(gray); axis image; % Affiche le visage reconstitué
% Section 11 : Reconnaissance d’un visage inconnu
I = imread("18-1.jpg"); % Charge une nouvelle image
UnknownCrop = extractFace(I); % Extrait le visage de l’image
imagesc(UnknownCrop) % Affiche le visage extrait
RegFace = reshape(UnknownCrop, [10000 1]); % Convertit le visage extrait en vecteur
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage extrait dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage extrait
imagesc(reshape(HFace, [100 100])); colormap(gray); % Affiche le visage reconstitué
———————————————————————————————————————————-
% Etape 1 : Conversion de l’image en espace de couleur YCbCr et détection de la région du visage
I5 = imread(‘path_to_image.jpg’); % Charger l’image (remplace ‘path_to_image.jpg’ par le chemin réel)
YI = rgb2ycbcr(I5); % Convertit l’image RGB en YCbCr
FaceArea = (YI(:, :, 3) > 140); % Crée une masque binaire pour détecter la région du visage
imagesc(FaceArea) % Affiche la région détectée
figure; plot(sum(FaceArea)) % Affiche la somme des pixels de la région détectée selon les colonnes
figure; plot(sum(FaceArea’)) % Affiche la somme des pixels de la région détectée selon les lignes
Xindices = find(sum(FaceArea) > 100); % Trouve les indices des colonnes avec une somme de pixels supérieure à 100
Xmin = min(Xindices); % Trouve l’indice minimum des colonnes
Xmax = max(Xindices); % Trouve l’indice maximum des colonnes
Yindices = find(sum(FaceArea’) > 100); % Trouve les indices des lignes avec une somme de pixels supérieure à 100
Ymin = min(Yindices); % Trouve l’indice minimum des lignes
Ymax = max(Yindices); % Trouve l’indice maximum des lignes
% Etape 2 : Détection des cercles (yeux) dans l’image
I = imread(’23-1.jpg’); % Charger une nouvelle image
[centersDark, radiiDark] = imfindcircles(rgb2gray(I), [25 50], ‘ObjectPolarity’, ‘dark’, ‘Sensitivity’, 0.9); % Trouve les cercles dans l’image
image(I) % Affiche l’image
viscircles(centersDark, radiiDark, ‘EdgeColor’, ‘y’) % Superpose les cercles détectés sur l’image
% Dernière étape : PCA pour la reconnaissance faciale
% Etape 3 : Chargement des données de visages
load(‘faces.mat’) % Charger les données de visages préalablement sauvegardées
% Etape 4 : Conversion des images de visages en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
% Etape 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
% Etape 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Etape 7 : Décomposition en valeurs singulières (SVD)
[U, S, V] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Etape 13 : Projection des visages d’entraînement dans l’espace des visages
LowTrainFaces = U’ * A; % Projette les visages d’entraînement dans l’espace des visages
% Etape 14 : Reconnaissance d’un visage inconnu
I = imread(’21-4.jpg’); % Charge une nouvelle image
Crop = extractFace(I); % Extrait le visage de l’image
imagesc(Crop) % Affiche le visage extrait
UnknownVec = reshape(Crop, [10000 1]); % Convertit le visage extrait en vecteur
LowUnknownVec = U’ * (double(UnknownVec) – averageFace); % Projette le visage extrait dans l’espace des visages
EuclideanDist = sqrt(sum((LowTrainFaces – LowUnknownVec).^2)); % Calcule la distance euclidienne entre le visage inconnu et les visages d’entraînement
[minDist, minIndex] = min(EuclideanDist); % Trouve la distance minimale et l’index du visage correspondant
figure; imagesc(Face(:, :, minIndex)) % Affiche le visage correspondant
[sortDist, sortIndex] = sort(EuclideanDist, ‘ascend’); % Trie les distances euclidiennes par ordre croissant
imagesc(Face(:, :, sortIndex(7))) % Affiche le septième visage le plus proche% Section 1 : Chargement des noms de fichiers et dates
filenames = dir; % Récupère la liste des fichiers dans le répertoire courant
clear files dates % Efface les variables ‘files’ et ‘dates’ si elles existent
for i = 3:size(filenames, 1) % Boucle à partir du troisième élément pour ignorer ‘.’ et ‘..’
files{i-2} = filenames(i).name; % Stocke le nom du fichier dans ‘files’
dates{i-2} = filenames(i).date; % Stocke la date du fichier dans ‘dates’
end
% Section 2 : Chargement des images
clear I % Efface la variable ‘I’ si elle existe
ii = 1; % Initialise l’index pour les images chargées
for i = 1:size(files, 2) % Boucle sur tous les fichiers
try
I{ii} = imread(files{i}); % Tente de lire l’image et la stocke dans ‘I’
ii = ii + 1; % Incrémente l’index
catch
i % Affiche l’index de l’image qui ne peut pas être lue
end
end
% Section 3 : Extraction des visages
for i = 1:29 % Boucle sur les 29 premières images
Face(:, :, i) = extractFace(I{i}); % Extrait le visage de l’image et le stocke dans ‘Face’
end
for i = 1:29 % Boucle pour afficher les visages extraits
figure
image(Face(:, :, i)); colormap(gray); % Affiche le visage en niveaux de gris
end
% Section 4 : Conversion des images en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
imagesc(X) % Affiche la matrice ‘X’ sous forme d’image
% Section 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
imagesc(reshape(averageFace, [100 100])); colormap(gray); % Affiche le visage moyen
% Section 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Section 7 : Décomposition en valeurs singulières (SVD)
[U, S, D] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Section 8 : Affichage des valeurs singulières
diag(S) % Affiche les valeurs singulières sous forme de vecteur diagonal
% Section 9 : Affichage des Eigenfaces
for i = 1:9 % Boucle pour afficher les 9 premiers eigenfaces
figure
imagesc(reshape(U(:, i), [100 100])); % Affiche chaque eigenface
colormap(gray);
end
% Section 10 : Reconnaissance de visage
RegFace = X(:, 9); % Sélectionne un visage de référence dans ‘X’
imagesc(reshape(RegFace, [100 100])); colormap(gray); axis image; % Affiche le visage de référence
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage de référence dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage à partir de l’espace des visages
imagesc(reshape(HFace, [100 100])); colormap(gray); axis image; % Affiche le visage reconstitué
% Section 11 : Reconnaissance d’un visage inconnu
I = imread("18-1.jpg"); % Charge une nouvelle image
UnknownCrop = extractFace(I); % Extrait le visage de l’image
imagesc(UnknownCrop) % Affiche le visage extrait
RegFace = reshape(UnknownCrop, [10000 1]); % Convertit le visage extrait en vecteur
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage extrait dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage extrait
imagesc(reshape(HFace, [100 100])); colormap(gray); % Affiche le visage reconstitué
———————————————————————————————————————————-
% Etape 1 : Conversion de l’image en espace de couleur YCbCr et détection de la région du visage
I5 = imread(‘path_to_image.jpg’); % Charger l’image (remplace ‘path_to_image.jpg’ par le chemin réel)
YI = rgb2ycbcr(I5); % Convertit l’image RGB en YCbCr
FaceArea = (YI(:, :, 3) > 140); % Crée une masque binaire pour détecter la région du visage
imagesc(FaceArea) % Affiche la région détectée
figure; plot(sum(FaceArea)) % Affiche la somme des pixels de la région détectée selon les colonnes
figure; plot(sum(FaceArea’)) % Affiche la somme des pixels de la région détectée selon les lignes
Xindices = find(sum(FaceArea) > 100); % Trouve les indices des colonnes avec une somme de pixels supérieure à 100
Xmin = min(Xindices); % Trouve l’indice minimum des colonnes
Xmax = max(Xindices); % Trouve l’indice maximum des colonnes
Yindices = find(sum(FaceArea’) > 100); % Trouve les indices des lignes avec une somme de pixels supérieure à 100
Ymin = min(Yindices); % Trouve l’indice minimum des lignes
Ymax = max(Yindices); % Trouve l’indice maximum des lignes
% Etape 2 : Détection des cercles (yeux) dans l’image
I = imread(’23-1.jpg’); % Charger une nouvelle image
[centersDark, radiiDark] = imfindcircles(rgb2gray(I), [25 50], ‘ObjectPolarity’, ‘dark’, ‘Sensitivity’, 0.9); % Trouve les cercles dans l’image
image(I) % Affiche l’image
viscircles(centersDark, radiiDark, ‘EdgeColor’, ‘y’) % Superpose les cercles détectés sur l’image
% Dernière étape : PCA pour la reconnaissance faciale
% Etape 3 : Chargement des données de visages
load(‘faces.mat’) % Charger les données de visages préalablement sauvegardées
% Etape 4 : Conversion des images de visages en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
% Etape 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
% Etape 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Etape 7 : Décomposition en valeurs singulières (SVD)
[U, S, V] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Etape 13 : Projection des visages d’entraînement dans l’espace des visages
LowTrainFaces = U’ * A; % Projette les visages d’entraînement dans l’espace des visages
% Etape 14 : Reconnaissance d’un visage inconnu
I = imread(’21-4.jpg’); % Charge une nouvelle image
Crop = extractFace(I); % Extrait le visage de l’image
imagesc(Crop) % Affiche le visage extrait
UnknownVec = reshape(Crop, [10000 1]); % Convertit le visage extrait en vecteur
LowUnknownVec = U’ * (double(UnknownVec) – averageFace); % Projette le visage extrait dans l’espace des visages
EuclideanDist = sqrt(sum((LowTrainFaces – LowUnknownVec).^2)); % Calcule la distance euclidienne entre le visage inconnu et les visages d’entraînement
[minDist, minIndex] = min(EuclideanDist); % Trouve la distance minimale et l’index du visage correspondant
figure; imagesc(Face(:, :, minIndex)) % Affiche le visage correspondant
[sortDist, sortIndex] = sort(EuclideanDist, ‘ascend’); % Trie les distances euclidiennes par ordre croissant
imagesc(Face(:, :, sortIndex(7))) % Affiche le septième visage le plus proche % Section 1 : Chargement des noms de fichiers et dates
filenames = dir; % Récupère la liste des fichiers dans le répertoire courant
clear files dates % Efface les variables ‘files’ et ‘dates’ si elles existent
for i = 3:size(filenames, 1) % Boucle à partir du troisième élément pour ignorer ‘.’ et ‘..’
files{i-2} = filenames(i).name; % Stocke le nom du fichier dans ‘files’
dates{i-2} = filenames(i).date; % Stocke la date du fichier dans ‘dates’
end
% Section 2 : Chargement des images
clear I % Efface la variable ‘I’ si elle existe
ii = 1; % Initialise l’index pour les images chargées
for i = 1:size(files, 2) % Boucle sur tous les fichiers
try
I{ii} = imread(files{i}); % Tente de lire l’image et la stocke dans ‘I’
ii = ii + 1; % Incrémente l’index
catch
i % Affiche l’index de l’image qui ne peut pas être lue
end
end
% Section 3 : Extraction des visages
for i = 1:29 % Boucle sur les 29 premières images
Face(:, :, i) = extractFace(I{i}); % Extrait le visage de l’image et le stocke dans ‘Face’
end
for i = 1:29 % Boucle pour afficher les visages extraits
figure
image(Face(:, :, i)); colormap(gray); % Affiche le visage en niveaux de gris
end
% Section 4 : Conversion des images en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
imagesc(X) % Affiche la matrice ‘X’ sous forme d’image
% Section 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
imagesc(reshape(averageFace, [100 100])); colormap(gray); % Affiche le visage moyen
% Section 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Section 7 : Décomposition en valeurs singulières (SVD)
[U, S, D] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Section 8 : Affichage des valeurs singulières
diag(S) % Affiche les valeurs singulières sous forme de vecteur diagonal
% Section 9 : Affichage des Eigenfaces
for i = 1:9 % Boucle pour afficher les 9 premiers eigenfaces
figure
imagesc(reshape(U(:, i), [100 100])); % Affiche chaque eigenface
colormap(gray);
end
% Section 10 : Reconnaissance de visage
RegFace = X(:, 9); % Sélectionne un visage de référence dans ‘X’
imagesc(reshape(RegFace, [100 100])); colormap(gray); axis image; % Affiche le visage de référence
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage de référence dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage à partir de l’espace des visages
imagesc(reshape(HFace, [100 100])); colormap(gray); axis image; % Affiche le visage reconstitué
% Section 11 : Reconnaissance d’un visage inconnu
I = imread("18-1.jpg"); % Charge une nouvelle image
UnknownCrop = extractFace(I); % Extrait le visage de l’image
imagesc(UnknownCrop) % Affiche le visage extrait
RegFace = reshape(UnknownCrop, [10000 1]); % Convertit le visage extrait en vecteur
LFace = U’ * (double(RegFace) – averageFace); % Projette le visage extrait dans l’espace des visages
HFace = U * LFace + averageFace; % Reconstitue le visage extrait
imagesc(reshape(HFace, [100 100])); colormap(gray); % Affiche le visage reconstitué
———————————————————————————————————————————-
% Etape 1 : Conversion de l’image en espace de couleur YCbCr et détection de la région du visage
I5 = imread(‘path_to_image.jpg’); % Charger l’image (remplace ‘path_to_image.jpg’ par le chemin réel)
YI = rgb2ycbcr(I5); % Convertit l’image RGB en YCbCr
FaceArea = (YI(:, :, 3) > 140); % Crée une masque binaire pour détecter la région du visage
imagesc(FaceArea) % Affiche la région détectée
figure; plot(sum(FaceArea)) % Affiche la somme des pixels de la région détectée selon les colonnes
figure; plot(sum(FaceArea’)) % Affiche la somme des pixels de la région détectée selon les lignes
Xindices = find(sum(FaceArea) > 100); % Trouve les indices des colonnes avec une somme de pixels supérieure à 100
Xmin = min(Xindices); % Trouve l’indice minimum des colonnes
Xmax = max(Xindices); % Trouve l’indice maximum des colonnes
Yindices = find(sum(FaceArea’) > 100); % Trouve les indices des lignes avec une somme de pixels supérieure à 100
Ymin = min(Yindices); % Trouve l’indice minimum des lignes
Ymax = max(Yindices); % Trouve l’indice maximum des lignes
% Etape 2 : Détection des cercles (yeux) dans l’image
I = imread(’23-1.jpg’); % Charger une nouvelle image
[centersDark, radiiDark] = imfindcircles(rgb2gray(I), [25 50], ‘ObjectPolarity’, ‘dark’, ‘Sensitivity’, 0.9); % Trouve les cercles dans l’image
image(I) % Affiche l’image
viscircles(centersDark, radiiDark, ‘EdgeColor’, ‘y’) % Superpose les cercles détectés sur l’image
% Dernière étape : PCA pour la reconnaissance faciale
% Etape 3 : Chargement des données de visages
load(‘faces.mat’) % Charger les données de visages préalablement sauvegardées
% Etape 4 : Conversion des images de visages en vecteurs
clear X % Efface la variable ‘X’ si elle existe
for i = 1:29 % Boucle sur les 29 visages extraits
X(:, i) = reshape(Face(:, :, i), [10000 1]); % Convertit chaque visage en un vecteur de 10000 éléments
end
% Etape 5 : Calcul du visage moyen
averageFace = mean(X, 2); % Calcule le visage moyen en prenant la moyenne de chaque ligne de ‘X’
% Etape 6 : Soustraction du visage moyen
A = double(X) – averageFace; % Soustrait le visage moyen de chaque colonne de ‘X’
% Etape 7 : Décomposition en valeurs singulières (SVD)
[U, S, V] = svds(A, 15); % Effectue une SVD sur ‘A’ pour obtenir les 15 valeurs singulières et vecteurs principaux
% Etape 13 : Projection des visages d’entraînement dans l’espace des visages
LowTrainFaces = U’ * A; % Projette les visages d’entraînement dans l’espace des visages
% Etape 14 : Reconnaissance d’un visage inconnu
I = imread(’21-4.jpg’); % Charge une nouvelle image
Crop = extractFace(I); % Extrait le visage de l’image
imagesc(Crop) % Affiche le visage extrait
UnknownVec = reshape(Crop, [10000 1]); % Convertit le visage extrait en vecteur
LowUnknownVec = U’ * (double(UnknownVec) – averageFace); % Projette le visage extrait dans l’espace des visages
EuclideanDist = sqrt(sum((LowTrainFaces – LowUnknownVec).^2)); % Calcule la distance euclidienne entre le visage inconnu et les visages d’entraînement
[minDist, minIndex] = min(EuclideanDist); % Trouve la distance minimale et l’index du visage correspondant
figure; imagesc(Face(:, :, minIndex)) % Affiche le visage correspondant
[sortDist, sortIndex] = sort(EuclideanDist, ‘ascend’); % Trie les distances euclidiennes par ordre croissant
imagesc(Face(:, :, sortIndex(7))) % Affiche le septième visage le plus proche pca MATLAB Answers — New Questions
Remove NaNs from struct fields embedded in a cell array
Good afternoon,
I have a strange problem occuring when using import data has started adding random lines of NaNs, I do not know why this has happened but I need to remove them.
Within the attached sample, the struct is contained within a cell array, as the original code loops. WIthin the struct, the data field contains the 2D matrix, what I need this for any rows with NaN added to be removed from each one.
Can you help please?
ThanksGood afternoon,
I have a strange problem occuring when using import data has started adding random lines of NaNs, I do not know why this has happened but I need to remove them.
Within the attached sample, the struct is contained within a cell array, as the original code loops. WIthin the struct, the data field contains the 2D matrix, what I need this for any rows with NaN added to be removed from each one.
Can you help please?
Thanks Good afternoon,
I have a strange problem occuring when using import data has started adding random lines of NaNs, I do not know why this has happened but I need to remove them.
Within the attached sample, the struct is contained within a cell array, as the original code loops. WIthin the struct, the data field contains the 2D matrix, what I need this for any rows with NaN added to be removed from each one.
Can you help please?
Thanks struct, cell array, nan MATLAB Answers — New Questions
After installing MATLAB 2024a, I get the following warnings and errors after startup
Warning: Initializing Java preferences failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:dispatcher:loadLibrary
C:Program FilesMATLABR2024abinwin64mcr.dll
Error using ismcc
C:Program FilesMATLABR2024abinwin64mcr.dll
Error occurred during deviceplugindetection initialization: C:Program
FilesMATLABR2024abinwin64mcr.dllWarning: Initializing Java preferences failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:dispatcher:loadLibrary
C:Program FilesMATLABR2024abinwin64mcr.dll
Error using ismcc
C:Program FilesMATLABR2024abinwin64mcr.dll
Error occurred during deviceplugindetection initialization: C:Program
FilesMATLABR2024abinwin64mcr.dll Warning: Initializing Java preferences failed in matlabrc.
This indicates a potentially serious problem in your MATLAB setup, which should be resolved as soon as possible. Error detected was:
MATLAB:dispatcher:loadLibrary
C:Program FilesMATLABR2024abinwin64mcr.dll
Error using ismcc
C:Program FilesMATLABR2024abinwin64mcr.dll
Error occurred during deviceplugindetection initialization: C:Program
FilesMATLABR2024abinwin64mcr.dll startup failure MATLAB Answers — New Questions
Problem With Deep Learning Toolbox
Im trying to open the Deep Learning Toolbox. The following error is returned:
Error using deepNetworkDesigner (line 29)
Invalid default value for property ‘Network’ in class ‘deepapp.internal.editor.import.NoArgsCallStrategy’:
Undefined function ‘mtimes’ for input arguments of type ‘nnet.cnn.layer.Layer’.
Similarly while calling a pretianed network in a code, following error is returned:
lgraphGoogLeNet = layerGraph(googlenet);
Warning: While loading an object of class ‘DAGNetwork’:
Too many input arguments.
Dot indexing is not supported for variables of this type.
Error in DAGNetwork/get.LayerGraph (line 188)
val = this.PrivateNetwork.LayerGraph;
Error in DAGNetwork/getLayerGraph (line 230)
layerGraph = this.LayerGraph;
Error in DAGNetwork/layerGraph (line 12)
internalLayerGraph = this.getLayerGraph();Im trying to open the Deep Learning Toolbox. The following error is returned:
Error using deepNetworkDesigner (line 29)
Invalid default value for property ‘Network’ in class ‘deepapp.internal.editor.import.NoArgsCallStrategy’:
Undefined function ‘mtimes’ for input arguments of type ‘nnet.cnn.layer.Layer’.
Similarly while calling a pretianed network in a code, following error is returned:
lgraphGoogLeNet = layerGraph(googlenet);
Warning: While loading an object of class ‘DAGNetwork’:
Too many input arguments.
Dot indexing is not supported for variables of this type.
Error in DAGNetwork/get.LayerGraph (line 188)
val = this.PrivateNetwork.LayerGraph;
Error in DAGNetwork/getLayerGraph (line 230)
layerGraph = this.LayerGraph;
Error in DAGNetwork/layerGraph (line 12)
internalLayerGraph = this.getLayerGraph(); Im trying to open the Deep Learning Toolbox. The following error is returned:
Error using deepNetworkDesigner (line 29)
Invalid default value for property ‘Network’ in class ‘deepapp.internal.editor.import.NoArgsCallStrategy’:
Undefined function ‘mtimes’ for input arguments of type ‘nnet.cnn.layer.Layer’.
Similarly while calling a pretianed network in a code, following error is returned:
lgraphGoogLeNet = layerGraph(googlenet);
Warning: While loading an object of class ‘DAGNetwork’:
Too many input arguments.
Dot indexing is not supported for variables of this type.
Error in DAGNetwork/get.LayerGraph (line 188)
val = this.PrivateNetwork.LayerGraph;
Error in DAGNetwork/getLayerGraph (line 230)
layerGraph = this.LayerGraph;
Error in DAGNetwork/layerGraph (line 12)
internalLayerGraph = this.getLayerGraph(); matlab, deep learning, toolbox MATLAB Answers — New Questions
No usable results when using insEKF() instead of imufilter()
Part of what I want to do is fuse gyroscope and accelerometer data to get an orientation estimate. When I fuse the data using the imufilter() I get results looking very similar to what I am expecting, without majorly tweaking the noise settings and so on.
I then proceeded to try to fuse it using the insEKF() because I eventually also need to fuse GPS measurements. For the first part I only added the gyroscope and the accelerometer to see the orientation estimate. I coded it very similar to the example in the documentation but for some reason the estimated orientation just start spinning and jumping around "uncontrollably".
Heres part of how Ive implemented it:
I also tried tuning it using the data I got from the other filter but that not seems like the issue. Also fusing the data sequentially using fuse() didnt change anything.
…
gyrofix=[gyro(:,2) gyro(:,3) gyro(:,1)]; %data already in workspace
acclfix=[-accl(:,2) -accl(:,3) -accl(:,1)];
option = insOptions(ReferenceFrame="ENU");
insAccel=insAccelerometer;
insGyro=insGyroscope;
tt_meas=timetable(acclfix,gyrofix,’RowTimes’, seconds(0:0.01:(size(acclfix,1)/100)-0.01))
tt_meas.Properties.VariableNames={‘Accelerometer’ ‘Gyroscope’}
tt_meas.Accelerometer(:,:)=0;
filt = insEKF(insAccel, insGyro, option);
initOrient=quaternion(1, 0, 0, 0);
stateparts(filt,"Orientation",compact(initOrient));
statecovparts(filt,"Orientation",0.01);
mnoise=tunernoise(filt);
mnoise.AccelerometerNoise=0.0002;
mnoise.GyroscopeNoise=9e-5;
untunedEst = estimateStates(filt,tt_meas,mnoise);Part of what I want to do is fuse gyroscope and accelerometer data to get an orientation estimate. When I fuse the data using the imufilter() I get results looking very similar to what I am expecting, without majorly tweaking the noise settings and so on.
I then proceeded to try to fuse it using the insEKF() because I eventually also need to fuse GPS measurements. For the first part I only added the gyroscope and the accelerometer to see the orientation estimate. I coded it very similar to the example in the documentation but for some reason the estimated orientation just start spinning and jumping around "uncontrollably".
Heres part of how Ive implemented it:
I also tried tuning it using the data I got from the other filter but that not seems like the issue. Also fusing the data sequentially using fuse() didnt change anything.
…
gyrofix=[gyro(:,2) gyro(:,3) gyro(:,1)]; %data already in workspace
acclfix=[-accl(:,2) -accl(:,3) -accl(:,1)];
option = insOptions(ReferenceFrame="ENU");
insAccel=insAccelerometer;
insGyro=insGyroscope;
tt_meas=timetable(acclfix,gyrofix,’RowTimes’, seconds(0:0.01:(size(acclfix,1)/100)-0.01))
tt_meas.Properties.VariableNames={‘Accelerometer’ ‘Gyroscope’}
tt_meas.Accelerometer(:,:)=0;
filt = insEKF(insAccel, insGyro, option);
initOrient=quaternion(1, 0, 0, 0);
stateparts(filt,"Orientation",compact(initOrient));
statecovparts(filt,"Orientation",0.01);
mnoise=tunernoise(filt);
mnoise.AccelerometerNoise=0.0002;
mnoise.GyroscopeNoise=9e-5;
untunedEst = estimateStates(filt,tt_meas,mnoise); Part of what I want to do is fuse gyroscope and accelerometer data to get an orientation estimate. When I fuse the data using the imufilter() I get results looking very similar to what I am expecting, without majorly tweaking the noise settings and so on.
I then proceeded to try to fuse it using the insEKF() because I eventually also need to fuse GPS measurements. For the first part I only added the gyroscope and the accelerometer to see the orientation estimate. I coded it very similar to the example in the documentation but for some reason the estimated orientation just start spinning and jumping around "uncontrollably".
Heres part of how Ive implemented it:
I also tried tuning it using the data I got from the other filter but that not seems like the issue. Also fusing the data sequentially using fuse() didnt change anything.
…
gyrofix=[gyro(:,2) gyro(:,3) gyro(:,1)]; %data already in workspace
acclfix=[-accl(:,2) -accl(:,3) -accl(:,1)];
option = insOptions(ReferenceFrame="ENU");
insAccel=insAccelerometer;
insGyro=insGyroscope;
tt_meas=timetable(acclfix,gyrofix,’RowTimes’, seconds(0:0.01:(size(acclfix,1)/100)-0.01))
tt_meas.Properties.VariableNames={‘Accelerometer’ ‘Gyroscope’}
tt_meas.Accelerometer(:,:)=0;
filt = insEKF(insAccel, insGyro, option);
initOrient=quaternion(1, 0, 0, 0);
stateparts(filt,"Orientation",compact(initOrient));
statecovparts(filt,"Orientation",0.01);
mnoise=tunernoise(filt);
mnoise.AccelerometerNoise=0.0002;
mnoise.GyroscopeNoise=9e-5;
untunedEst = estimateStates(filt,tt_meas,mnoise); sensor fusion, inertial, filter, ekf, insekf MATLAB Answers — New Questions
How to find the line of intersection between the following two planes and plot the intersected line on the same two planes?
How to find the line of intersection between the following two planes and plot the intersected line on the same two planes?
The following points contain the following points:
The first plane:
P1 = 177668442.453315 -102576923.076923 0
P2 = -102576923.076923 177668442.453315 -102576923.076923
P3= 0 -102576923.076923 88834221.2266576
The secod Plane:
P1= 152763459.308716 -102576923.076923 0
P2= -102576923.076923 183536536.231793 -102576923.076923
P3= 0 -102576923.076923 91768268.1158967How to find the line of intersection between the following two planes and plot the intersected line on the same two planes?
The following points contain the following points:
The first plane:
P1 = 177668442.453315 -102576923.076923 0
P2 = -102576923.076923 177668442.453315 -102576923.076923
P3= 0 -102576923.076923 88834221.2266576
The secod Plane:
P1= 152763459.308716 -102576923.076923 0
P2= -102576923.076923 183536536.231793 -102576923.076923
P3= 0 -102576923.076923 91768268.1158967 How to find the line of intersection between the following two planes and plot the intersected line on the same two planes?
The following points contain the following points:
The first plane:
P1 = 177668442.453315 -102576923.076923 0
P2 = -102576923.076923 177668442.453315 -102576923.076923
P3= 0 -102576923.076923 88834221.2266576
The secod Plane:
P1= 152763459.308716 -102576923.076923 0
P2= -102576923.076923 183536536.231793 -102576923.076923
P3= 0 -102576923.076923 91768268.1158967 plane, calculus, mathematics, plot MATLAB Answers — New Questions
can anyone have MATLAB code for dual tier cluster based routing protocol for wireless sensor network or any basic code related to this
can anyone have MATLAB code for dual tier cluster based routing protocol for wireless sensor network or any basic code related to thiscan anyone have MATLAB code for dual tier cluster based routing protocol for wireless sensor network or any basic code related to this can anyone have MATLAB code for dual tier cluster based routing protocol for wireless sensor network or any basic code related to this mobile wsn routing protocol matlab code MATLAB Answers — New Questions
How to build complex DL 5G waveform with multiple UEs, Layers and Precoding
I’m looking for examples to build complex 5G DL waveform which includes multiple UEs with different RBs per user, different number of Layes per user and different Precoding (beamforming) per user.I’m looking for examples to build complex 5G DL waveform which includes multiple UEs with different RBs per user, different number of Layes per user and different Precoding (beamforming) per user. I’m looking for examples to build complex 5G DL waveform which includes multiple UEs with different RBs per user, different number of Layes per user and different Precoding (beamforming) per user. 5g MATLAB Answers — New Questions
Derivation of noisy signal through Savitzky-Golay
I want to get an approximation of a noisy signal’s second derivative through the use of a Savitzky-Golay differentation matrix. The final goal is to (1) smooth out and (2) drastically downsample the initial signal without losing information. I was inspired for this idea by Jan’s post on https://nl.mathworks.com/matlabcentral/answers/1454924-downsample-data-adapively-intelligently where they used the gradient function to determine where the represented data has the strongest curvature and hence where it needs the most points.
The result is pretty much what I hoped for except for the edges of my domain where absent data is assumed to be zero which creates strong gradients across the width of the filter. This issue is not as impactful on the smoothing as it is on the derivation. In fact, function sgolayfilt satisfyingly corrects the edge effect from the straight up use of sgolay as explained in this https://nl.mathworks.com/help/signal/ref/sgolayfilt.html thread.
Then my problem is: how can I similarly resolve this effect on the approximated second derivative? I tried looking into the theory of this but it confuses me a little.
My current solution to the limitations of this filter was to equate the estimated derivative on these data points close to the edges to the closest value I was able to estimate properly. Here is the code I came up with so far:
%sgFilter – Adaptative downsampling using a Savitzky-Golay filter
%
% This MATLAB function uses a Savitzky-Golay differentiation filter in
% order to successively smooth out a signal x(t) and reduce its sample
% size down to n datapoints. An estimate of the 2nd derivative through
% the lens of the filter allows to map out the curvature of the signal
% without concern for the noise and helps identify hotspots needed for
% the accurate representation of the signal after downsampling.
%
% y filtered signal
% y(idx) filtered and sampled signal
% . . . .
% dt uniform step size
% order polynomial regression order
% window filter band width
%
% [y, idx] = sgFilter(x, dt, order, window, n)
function [y, idx] = sgFilter(x, dt, order, window, n)
% ———————————————————————–
% Savitzky-Golay differentiation matrices
[b, g] = sgolay(order, window);
m = (window – 1)/2;
% ———————————————————————–
% p-th order derivative estimates, i.e. 0: smooth and 2: 2nd derivative
dx = zeros(length(x), 2);
i = 0;
for p = [0, 2]
i = i + 1;
dx(:,i) = conv(x, factorial(p)/(-dt)^p * g(:, p + 1), ‘same’);
end
% ———————————————————————–
% Correction of the edge effect on smoothing
y = dx(:, 1); % Smoothed signal
y(1:m) = b(1:m, :)*x(1:window);
y(end – m + 1:end) = b(window – m + 1:window, :)*x(end – window + 1:end);
dy = dx(:, 2); % Smoothed signal’s derivative
dy(1:m) = dy(m + 1);
dy(end – m + 1:end) = dy(end – m);
% ———————————————————————–
% Adaptative downsampling, inspired from Jan at <https://nl.mathworks.com
% /matlabcentral/answers/1454924-downsample-data-adapively-intelligently>
% (17th May 2024).
if nargout > 1
sy = cumsum(abs(dy));
sy = sy + linspace(0, max(sy)/100, numel(sy)).’; % Monotonic increasing
idx = interp1(sy, 1:numel(sy), linspace(sy(1), sy(end), n), ‘nearest’);
end
And following is a test script I created with this function and the associated result:
% ————————————————————————-
% One should note that the success of this method is very dependent on the
% choice of polynomial regression order and window band width. In the
% particular case of periodic signals, the window should be wide enough to
% encompass periods with corresponding polynomial behaviour—e.g. a full
% sin(x) rotation from x to x + 2*pi cannot be represented accurately by a
% polynome of lower degree than 3, nor will it always be advantageous to
% have a degree higher than 3 due to Runge’s phenomenon. On this note, one
% should be conscious of the size of the window relative to the overall
% behaviour of the signal.
% ————————————————————————-
dt = 0.05;
t = (0:dt:20-1)’;
order = 3;
window = 51;
x = 5*sin(2*pi*0.2*t)+0.5*randn(size(t));
[y, idx] = sgFilter(x, dt, order, window, 60);
plot(t, x, ‘-k’)
hold on
plot(t, y, ‘-r’)
plot(t(idx), y(idx), ‘ro’)
hold off
legend(‘x’,’x (smoothed)’,’x (sampled)’)
As you can see, the current band width of the filter is approximately 2.5 long on the horizontal axis and half of that window is impacted by the edge effect with an overrepresentation close to t = 0 and an underrepresentation on the other end.I want to get an approximation of a noisy signal’s second derivative through the use of a Savitzky-Golay differentation matrix. The final goal is to (1) smooth out and (2) drastically downsample the initial signal without losing information. I was inspired for this idea by Jan’s post on https://nl.mathworks.com/matlabcentral/answers/1454924-downsample-data-adapively-intelligently where they used the gradient function to determine where the represented data has the strongest curvature and hence where it needs the most points.
The result is pretty much what I hoped for except for the edges of my domain where absent data is assumed to be zero which creates strong gradients across the width of the filter. This issue is not as impactful on the smoothing as it is on the derivation. In fact, function sgolayfilt satisfyingly corrects the edge effect from the straight up use of sgolay as explained in this https://nl.mathworks.com/help/signal/ref/sgolayfilt.html thread.
Then my problem is: how can I similarly resolve this effect on the approximated second derivative? I tried looking into the theory of this but it confuses me a little.
My current solution to the limitations of this filter was to equate the estimated derivative on these data points close to the edges to the closest value I was able to estimate properly. Here is the code I came up with so far:
%sgFilter – Adaptative downsampling using a Savitzky-Golay filter
%
% This MATLAB function uses a Savitzky-Golay differentiation filter in
% order to successively smooth out a signal x(t) and reduce its sample
% size down to n datapoints. An estimate of the 2nd derivative through
% the lens of the filter allows to map out the curvature of the signal
% without concern for the noise and helps identify hotspots needed for
% the accurate representation of the signal after downsampling.
%
% y filtered signal
% y(idx) filtered and sampled signal
% . . . .
% dt uniform step size
% order polynomial regression order
% window filter band width
%
% [y, idx] = sgFilter(x, dt, order, window, n)
function [y, idx] = sgFilter(x, dt, order, window, n)
% ———————————————————————–
% Savitzky-Golay differentiation matrices
[b, g] = sgolay(order, window);
m = (window – 1)/2;
% ———————————————————————–
% p-th order derivative estimates, i.e. 0: smooth and 2: 2nd derivative
dx = zeros(length(x), 2);
i = 0;
for p = [0, 2]
i = i + 1;
dx(:,i) = conv(x, factorial(p)/(-dt)^p * g(:, p + 1), ‘same’);
end
% ———————————————————————–
% Correction of the edge effect on smoothing
y = dx(:, 1); % Smoothed signal
y(1:m) = b(1:m, :)*x(1:window);
y(end – m + 1:end) = b(window – m + 1:window, :)*x(end – window + 1:end);
dy = dx(:, 2); % Smoothed signal’s derivative
dy(1:m) = dy(m + 1);
dy(end – m + 1:end) = dy(end – m);
% ———————————————————————–
% Adaptative downsampling, inspired from Jan at <https://nl.mathworks.com
% /matlabcentral/answers/1454924-downsample-data-adapively-intelligently>
% (17th May 2024).
if nargout > 1
sy = cumsum(abs(dy));
sy = sy + linspace(0, max(sy)/100, numel(sy)).’; % Monotonic increasing
idx = interp1(sy, 1:numel(sy), linspace(sy(1), sy(end), n), ‘nearest’);
end
And following is a test script I created with this function and the associated result:
% ————————————————————————-
% One should note that the success of this method is very dependent on the
% choice of polynomial regression order and window band width. In the
% particular case of periodic signals, the window should be wide enough to
% encompass periods with corresponding polynomial behaviour—e.g. a full
% sin(x) rotation from x to x + 2*pi cannot be represented accurately by a
% polynome of lower degree than 3, nor will it always be advantageous to
% have a degree higher than 3 due to Runge’s phenomenon. On this note, one
% should be conscious of the size of the window relative to the overall
% behaviour of the signal.
% ————————————————————————-
dt = 0.05;
t = (0:dt:20-1)’;
order = 3;
window = 51;
x = 5*sin(2*pi*0.2*t)+0.5*randn(size(t));
[y, idx] = sgFilter(x, dt, order, window, 60);
plot(t, x, ‘-k’)
hold on
plot(t, y, ‘-r’)
plot(t(idx), y(idx), ‘ro’)
hold off
legend(‘x’,’x (smoothed)’,’x (sampled)’)
As you can see, the current band width of the filter is approximately 2.5 long on the horizontal axis and half of that window is impacted by the edge effect with an overrepresentation close to t = 0 and an underrepresentation on the other end. I want to get an approximation of a noisy signal’s second derivative through the use of a Savitzky-Golay differentation matrix. The final goal is to (1) smooth out and (2) drastically downsample the initial signal without losing information. I was inspired for this idea by Jan’s post on https://nl.mathworks.com/matlabcentral/answers/1454924-downsample-data-adapively-intelligently where they used the gradient function to determine where the represented data has the strongest curvature and hence where it needs the most points.
The result is pretty much what I hoped for except for the edges of my domain where absent data is assumed to be zero which creates strong gradients across the width of the filter. This issue is not as impactful on the smoothing as it is on the derivation. In fact, function sgolayfilt satisfyingly corrects the edge effect from the straight up use of sgolay as explained in this https://nl.mathworks.com/help/signal/ref/sgolayfilt.html thread.
Then my problem is: how can I similarly resolve this effect on the approximated second derivative? I tried looking into the theory of this but it confuses me a little.
My current solution to the limitations of this filter was to equate the estimated derivative on these data points close to the edges to the closest value I was able to estimate properly. Here is the code I came up with so far:
%sgFilter – Adaptative downsampling using a Savitzky-Golay filter
%
% This MATLAB function uses a Savitzky-Golay differentiation filter in
% order to successively smooth out a signal x(t) and reduce its sample
% size down to n datapoints. An estimate of the 2nd derivative through
% the lens of the filter allows to map out the curvature of the signal
% without concern for the noise and helps identify hotspots needed for
% the accurate representation of the signal after downsampling.
%
% y filtered signal
% y(idx) filtered and sampled signal
% . . . .
% dt uniform step size
% order polynomial regression order
% window filter band width
%
% [y, idx] = sgFilter(x, dt, order, window, n)
function [y, idx] = sgFilter(x, dt, order, window, n)
% ———————————————————————–
% Savitzky-Golay differentiation matrices
[b, g] = sgolay(order, window);
m = (window – 1)/2;
% ———————————————————————–
% p-th order derivative estimates, i.e. 0: smooth and 2: 2nd derivative
dx = zeros(length(x), 2);
i = 0;
for p = [0, 2]
i = i + 1;
dx(:,i) = conv(x, factorial(p)/(-dt)^p * g(:, p + 1), ‘same’);
end
% ———————————————————————–
% Correction of the edge effect on smoothing
y = dx(:, 1); % Smoothed signal
y(1:m) = b(1:m, :)*x(1:window);
y(end – m + 1:end) = b(window – m + 1:window, :)*x(end – window + 1:end);
dy = dx(:, 2); % Smoothed signal’s derivative
dy(1:m) = dy(m + 1);
dy(end – m + 1:end) = dy(end – m);
% ———————————————————————–
% Adaptative downsampling, inspired from Jan at <https://nl.mathworks.com
% /matlabcentral/answers/1454924-downsample-data-adapively-intelligently>
% (17th May 2024).
if nargout > 1
sy = cumsum(abs(dy));
sy = sy + linspace(0, max(sy)/100, numel(sy)).’; % Monotonic increasing
idx = interp1(sy, 1:numel(sy), linspace(sy(1), sy(end), n), ‘nearest’);
end
And following is a test script I created with this function and the associated result:
% ————————————————————————-
% One should note that the success of this method is very dependent on the
% choice of polynomial regression order and window band width. In the
% particular case of periodic signals, the window should be wide enough to
% encompass periods with corresponding polynomial behaviour—e.g. a full
% sin(x) rotation from x to x + 2*pi cannot be represented accurately by a
% polynome of lower degree than 3, nor will it always be advantageous to
% have a degree higher than 3 due to Runge’s phenomenon. On this note, one
% should be conscious of the size of the window relative to the overall
% behaviour of the signal.
% ————————————————————————-
dt = 0.05;
t = (0:dt:20-1)’;
order = 3;
window = 51;
x = 5*sin(2*pi*0.2*t)+0.5*randn(size(t));
[y, idx] = sgFilter(x, dt, order, window, 60);
plot(t, x, ‘-k’)
hold on
plot(t, y, ‘-r’)
plot(t(idx), y(idx), ‘ro’)
hold off
legend(‘x’,’x (smoothed)’,’x (sampled)’)
As you can see, the current band width of the filter is approximately 2.5 long on the horizontal axis and half of that window is impacted by the edge effect with an overrepresentation close to t = 0 and an underrepresentation on the other end. smoothing, derivative, downsampling MATLAB Answers — New Questions
I enabled fft function in oscillioscope and it saved the data as FFT amplitude (dBV) and frequency domain how ever I want my time domain and ampltude signals original data.
%%
folder = ‘C:UsershaneuOneDrive바탕 화면New folder (2)’;
filename = ‘550mvp.csv’;
data = readtable(fullfile(folder,filename));
frequency = table2array(data(3:end,1));
amplitude = table2array(data(3:end,2));
figure,plot(frequency/1e6,amplitude)
xlim([0,15])
xlabel(‘Frequency [MHz]’),
grid on,
ylabel(‘Amplitude[dBV]’)%%
folder = ‘C:UsershaneuOneDrive바탕 화면New folder (2)’;
filename = ‘550mvp.csv’;
data = readtable(fullfile(folder,filename));
frequency = table2array(data(3:end,1));
amplitude = table2array(data(3:end,2));
figure,plot(frequency/1e6,amplitude)
xlim([0,15])
xlabel(‘Frequency [MHz]’),
grid on,
ylabel(‘Amplitude[dBV]’) %%
folder = ‘C:UsershaneuOneDrive바탕 화면New folder (2)’;
filename = ‘550mvp.csv’;
data = readtable(fullfile(folder,filename));
frequency = table2array(data(3:end,1));
amplitude = table2array(data(3:end,2));
figure,plot(frequency/1e6,amplitude)
xlim([0,15])
xlabel(‘Frequency [MHz]’),
grid on,
ylabel(‘Amplitude[dBV]’) signal processing, fft, data acquisition MATLAB Answers — New Questions
Convert to MATLAB Code
Post Content Post Content convert, matlab function, matlab MATLAB Answers — New Questions
Matlab 2022 Arduino Simulink Exceeding Memory Error
Hi,
I’ve done Simulink on Arduino with Matlab 2019b with success.
However, super annoyingly, Simulink Support Package For Arduino Hardware does not include much on Matlab 2019b. So I installed Matlab 2022 + needed add-ons and got way more features to aid my programming. Great!
Now, I suddenly get this error, even with a tiny program to make Digital Output 13 ( onboard LED) to blink with a impulse generator.
ERROR:
Top model targets built: Model Action Rebuild Reason ==================================================================== untitled Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 11.414s
The following error occurred during deployment to your hardware board: The generated code exceeds the available memory on the processor. It uses 134.2% of available program memory and 48.6% of available Data memory.
This doesnt make any sense. I then go back to my Matlab 2019b and make the same program without problems. So I would assume the problem is with Matlab 2022 version.
I’ve googled the error, but people are just saying "your program is taking to much space, try to make it smaller", which I dont think is the correct solution in my case.
Any ideas?
Hardware: Arduino Uno
COM : Automatically
Baudrate: 115200 ( Default)Hi,
I’ve done Simulink on Arduino with Matlab 2019b with success.
However, super annoyingly, Simulink Support Package For Arduino Hardware does not include much on Matlab 2019b. So I installed Matlab 2022 + needed add-ons and got way more features to aid my programming. Great!
Now, I suddenly get this error, even with a tiny program to make Digital Output 13 ( onboard LED) to blink with a impulse generator.
ERROR:
Top model targets built: Model Action Rebuild Reason ==================================================================== untitled Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 11.414s
The following error occurred during deployment to your hardware board: The generated code exceeds the available memory on the processor. It uses 134.2% of available program memory and 48.6% of available Data memory.
This doesnt make any sense. I then go back to my Matlab 2019b and make the same program without problems. So I would assume the problem is with Matlab 2022 version.
I’ve googled the error, but people are just saying "your program is taking to much space, try to make it smaller", which I dont think is the correct solution in my case.
Any ideas?
Hardware: Arduino Uno
COM : Automatically
Baudrate: 115200 ( Default) Hi,
I’ve done Simulink on Arduino with Matlab 2019b with success.
However, super annoyingly, Simulink Support Package For Arduino Hardware does not include much on Matlab 2019b. So I installed Matlab 2022 + needed add-ons and got way more features to aid my programming. Great!
Now, I suddenly get this error, even with a tiny program to make Digital Output 13 ( onboard LED) to blink with a impulse generator.
ERROR:
Top model targets built: Model Action Rebuild Reason ==================================================================== untitled Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 11.414s
The following error occurred during deployment to your hardware board: The generated code exceeds the available memory on the processor. It uses 134.2% of available program memory and 48.6% of available Data memory.
This doesnt make any sense. I then go back to my Matlab 2019b and make the same program without problems. So I would assume the problem is with Matlab 2022 version.
I’ve googled the error, but people are just saying "your program is taking to much space, try to make it smaller", which I dont think is the correct solution in my case.
Any ideas?
Hardware: Arduino Uno
COM : Automatically
Baudrate: 115200 ( Default) arduino, simulink, error, exceed, memory MATLAB Answers — New Questions