Category: Matlab
Category Archives: Matlab
phased.Receiver Noise Figure and SNR ratio
I’m trying to verify the definition of the Noise factor (or Noise figure, if in db) , i.e.
at the input and output of a receiver modelled as a phased.Receiver matlab system object.
rng(1, "twister"); % for repeatability
fs = 100e6;
f = 100e3;
time_array = 0:1/fs:1/f;
waveform = sin(2*pi*f*time_array);
SNR_i = 30; %dB
input = awgn(waveform, SNR_i, ‘measured’);
noise_input = input – waveform;
SNR_i = snr(waveform, noise_input); % So far, so good
gain = 30; %dB
noiseFigure = 20;
refTemp = 290;
rec = phased.Receiver(‘Gain’, gain, …
‘NoiseMethod’, ‘Noise figure’, …
‘NoiseFigure’, noiseFigure, …
‘ReferenceTemperature’, refTemp, …
‘SampleRate’, fs);
output = rec(input);
amplifiedSignalNoNoise = waveform*db2mag(gain);
plot(time_array, real(output)); hold on
plot(time_array, amplifiedSignalNoNoise, ‘LineWidth’, 2); hold off
noise_output = output – amplifiedSignalNoNoise;
SNR_o = snr(amplifiedSignalNoNoise, noise_output);
Unfortunately, I don’t find the 20 dB of Noise Figure when doing SNR_i – SNR_o. Same problem arrives if I use phased.Transmitter or phased.ReceiverPreamp. What am I missing?I’m trying to verify the definition of the Noise factor (or Noise figure, if in db) , i.e.
at the input and output of a receiver modelled as a phased.Receiver matlab system object.
rng(1, "twister"); % for repeatability
fs = 100e6;
f = 100e3;
time_array = 0:1/fs:1/f;
waveform = sin(2*pi*f*time_array);
SNR_i = 30; %dB
input = awgn(waveform, SNR_i, ‘measured’);
noise_input = input – waveform;
SNR_i = snr(waveform, noise_input); % So far, so good
gain = 30; %dB
noiseFigure = 20;
refTemp = 290;
rec = phased.Receiver(‘Gain’, gain, …
‘NoiseMethod’, ‘Noise figure’, …
‘NoiseFigure’, noiseFigure, …
‘ReferenceTemperature’, refTemp, …
‘SampleRate’, fs);
output = rec(input);
amplifiedSignalNoNoise = waveform*db2mag(gain);
plot(time_array, real(output)); hold on
plot(time_array, amplifiedSignalNoNoise, ‘LineWidth’, 2); hold off
noise_output = output – amplifiedSignalNoNoise;
SNR_o = snr(amplifiedSignalNoNoise, noise_output);
Unfortunately, I don’t find the 20 dB of Noise Figure when doing SNR_i – SNR_o. Same problem arrives if I use phased.Transmitter or phased.ReceiverPreamp. What am I missing? I’m trying to verify the definition of the Noise factor (or Noise figure, if in db) , i.e.
at the input and output of a receiver modelled as a phased.Receiver matlab system object.
rng(1, "twister"); % for repeatability
fs = 100e6;
f = 100e3;
time_array = 0:1/fs:1/f;
waveform = sin(2*pi*f*time_array);
SNR_i = 30; %dB
input = awgn(waveform, SNR_i, ‘measured’);
noise_input = input – waveform;
SNR_i = snr(waveform, noise_input); % So far, so good
gain = 30; %dB
noiseFigure = 20;
refTemp = 290;
rec = phased.Receiver(‘Gain’, gain, …
‘NoiseMethod’, ‘Noise figure’, …
‘NoiseFigure’, noiseFigure, …
‘ReferenceTemperature’, refTemp, …
‘SampleRate’, fs);
output = rec(input);
amplifiedSignalNoNoise = waveform*db2mag(gain);
plot(time_array, real(output)); hold on
plot(time_array, amplifiedSignalNoNoise, ‘LineWidth’, 2); hold off
noise_output = output – amplifiedSignalNoNoise;
SNR_o = snr(amplifiedSignalNoNoise, noise_output);
Unfortunately, I don’t find the 20 dB of Noise Figure when doing SNR_i – SNR_o. Same problem arrives if I use phased.Transmitter or phased.ReceiverPreamp. What am I missing? snr, phased.receiver MATLAB Answers — New Questions
MathWorksServiceHost issues (really slows down startup and then doesn’t stop when matlab stops) in 2024a
With 2024a on Linux, when the matlab process starts, MathWorksServiceHost and MathWorksServiceHost-Monitor are started from the user’s home directory, which REALLY slows down the startup when the home directory is mounted over the network. I’ve been able to mitigate the slowdown a bit by having $HOME/.MathWorks/ServiceHost get created a simlink to the local /tmp dir However…
MathWorksServiceHost and MathWorksServiceHost-Monitor don’t stop when the matlab process stops. This is a problem on a multi-user system where, we then have a bunch of processes just hanging around for no reason.
This first issue is a problem, but not too major an issue, but the second would seem to me to be a bug.With 2024a on Linux, when the matlab process starts, MathWorksServiceHost and MathWorksServiceHost-Monitor are started from the user’s home directory, which REALLY slows down the startup when the home directory is mounted over the network. I’ve been able to mitigate the slowdown a bit by having $HOME/.MathWorks/ServiceHost get created a simlink to the local /tmp dir However…
MathWorksServiceHost and MathWorksServiceHost-Monitor don’t stop when the matlab process stops. This is a problem on a multi-user system where, we then have a bunch of processes just hanging around for no reason.
This first issue is a problem, but not too major an issue, but the second would seem to me to be a bug. With 2024a on Linux, when the matlab process starts, MathWorksServiceHost and MathWorksServiceHost-Monitor are started from the user’s home directory, which REALLY slows down the startup when the home directory is mounted over the network. I’ve been able to mitigate the slowdown a bit by having $HOME/.MathWorks/ServiceHost get created a simlink to the local /tmp dir However…
MathWorksServiceHost and MathWorksServiceHost-Monitor don’t stop when the matlab process stops. This is a problem on a multi-user system where, we then have a bunch of processes just hanging around for no reason.
This first issue is a problem, but not too major an issue, but the second would seem to me to be a bug. mathworksservicehost MATLAB Answers — New Questions
How to apply functions to symmatrix objects, in the same way as to sym objects.
Hi
I work with symbolic matrix objects, defined as symmatrix.
Unfortunatly, symmatrix is not compatible with as many functions as a symbolic scalar (sym). In my case i would like to apply normcdf or equivalently erf to a symmatrix matrix (as an elementwise operation, like it could be done with a double matrix). This cant be done.
% works for scalars
syms y x;
a=erf(y*x);
b=normcdf(y*x);
diff(a,x)
diff(b,x)
% fails for symmatrix
Y = symmatrix(‘Y’,[2,1]);
syms x
a=erf(Y*x)
b=normcdf(Y*x)
diff(a,x)
diff(b,x)
I am wondering if there is a workaround via an abstract function. I thought maybe symfunmatrix helps, but I couldnt get it to do what I want.
Importantly, I dont want any conversion to sym, because I want to later use the resulting matrix expressions for numeric evaluation for arbitrary n. Conversion to sym would turn matrix expressions into element by element operatons and make the numeric evaluation slow.Hi
I work with symbolic matrix objects, defined as symmatrix.
Unfortunatly, symmatrix is not compatible with as many functions as a symbolic scalar (sym). In my case i would like to apply normcdf or equivalently erf to a symmatrix matrix (as an elementwise operation, like it could be done with a double matrix). This cant be done.
% works for scalars
syms y x;
a=erf(y*x);
b=normcdf(y*x);
diff(a,x)
diff(b,x)
% fails for symmatrix
Y = symmatrix(‘Y’,[2,1]);
syms x
a=erf(Y*x)
b=normcdf(Y*x)
diff(a,x)
diff(b,x)
I am wondering if there is a workaround via an abstract function. I thought maybe symfunmatrix helps, but I couldnt get it to do what I want.
Importantly, I dont want any conversion to sym, because I want to later use the resulting matrix expressions for numeric evaluation for arbitrary n. Conversion to sym would turn matrix expressions into element by element operatons and make the numeric evaluation slow. Hi
I work with symbolic matrix objects, defined as symmatrix.
Unfortunatly, symmatrix is not compatible with as many functions as a symbolic scalar (sym). In my case i would like to apply normcdf or equivalently erf to a symmatrix matrix (as an elementwise operation, like it could be done with a double matrix). This cant be done.
% works for scalars
syms y x;
a=erf(y*x);
b=normcdf(y*x);
diff(a,x)
diff(b,x)
% fails for symmatrix
Y = symmatrix(‘Y’,[2,1]);
syms x
a=erf(Y*x)
b=normcdf(Y*x)
diff(a,x)
diff(b,x)
I am wondering if there is a workaround via an abstract function. I thought maybe symfunmatrix helps, but I couldnt get it to do what I want.
Importantly, I dont want any conversion to sym, because I want to later use the resulting matrix expressions for numeric evaluation for arbitrary n. Conversion to sym would turn matrix expressions into element by element operatons and make the numeric evaluation slow. symmatrix, symbolic math toolbox MATLAB Answers — New Questions
How to draw a streamline diagram in a circular area?
Hi all, x and y are the coordinates of the circular region in the file, u and v are the velocity values in x and y directions in the corresponding coordinates, I can draw a vector diagram, but it ‘s hard to draw a streamline diagram, So I would like to know how to use the streamline function for a circular area.Hi all, x and y are the coordinates of the circular region in the file, u and v are the velocity values in x and y directions in the corresponding coordinates, I can draw a vector diagram, but it ‘s hard to draw a streamline diagram, So I would like to know how to use the streamline function for a circular area. Hi all, x and y are the coordinates of the circular region in the file, u and v are the velocity values in x and y directions in the corresponding coordinates, I can draw a vector diagram, but it ‘s hard to draw a streamline diagram, So I would like to know how to use the streamline function for a circular area. streamline, streamslice MATLAB Answers — New Questions
Identifying PTT of ECG and PPG signals
I’m trying to detect the pulse transit time between ecg and ppg signals. I have the ecg and ppg signals filtered and normalised around 1. Here is my code so far
clc;
clear;
close all;
All_Data = {}; % set up cell array for all workbook data
Plotted_Data_ECG_PPG = {}; % Set up cell array for ECG and PPG plotted data
% Parameters for moving average filter
windowSize = 2;
ecgThreshold = 0.375;
ppgThreshold = 0.1;
for i = 1:1 % set up loop to run for 11 iterations (no. of workbooks)
filename = sprintf(‘%03d.xlsx’, i); % set up each filename 001-011 to be read on each iteration
opt = detectImportOptions(filename); % import data from filename
sheets = sheetnames(filename); % retrieve names of sheets
for j = 1:numel(sheets) % iterate over each sheet within a workbook
tBC = readtable(filename, opt, ‘Sheet’, sheets{j}); % extract sheets from workbooks
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Remove invalid rows from table (corresponding to NaN’s in Time_Data
rows2delete = isnan(Time_Data);
tBC(rows2delete,:) = [];
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Fit a polynomial p of 1st degree to the first points of each staircase (top curve)
xx = (1:numel(Time_Data))’;
dTime_Data = diff(Time_Data);
ind = 1+find(dTime_Data>max(dTime_Data)/100);
ind = ind(2:end); % in some cases the first point is too much off trend and we prefer not to use it.
p = polyfit(xx(ind),Time_Data(ind),1);
% Evaluate the fitted polynomial p and plot:
Time_Data_new = polyval(p,xx);
% % debug plots (to double check)
% figure(j)
% plot(xx,Time_Data,xx,Time_Data_new);
ECG_Data = tBC{:, ‘Var6’}; % extract ECG data from column 6
PPG_Data = tBC{:, ‘Var8’}; % extract PPG data from column 8
SYS_Data = tBC{:, ‘Var10’}; % extract reference systolic pressure data from column 10
DIA_Data = tBC{:, ‘Var12’}; % extract reference diastolic pressure data from column 12
% Filter ECG and PPG data
ECG_Data_smoothed = movmean(ECG_Data, windowSize);
PPG_Data_smoothed = movmean(PPG_Data, windowSize);
% Normalize ECG and PPG data around 0
ECG_Data_normalized = ECG_Data_smoothed – mean(ECG_Data_smoothed);
PPG_Data_normalized = PPG_Data_smoothed – mean(PPG_Data_smoothed);
% Fnd peaks for ECG and PPG data above thresholds
[ecgPeaks, ecgPeakIdx] = findpeaks(ECG_Data_normalized, ‘MinPeakHeight’, ecgThreshold);
[ppgPeaks, ppgPeakIdx] = findpeaks(PPG_Data_normalized, ‘MinPeakHeight’, ppgThreshold);
Time_Formatted = datestr(Time_Data_new, ‘HH:MM:SS:fff’); % Format time data with milliseconds
t = datetime(Time_Formatted,’InputFormat’,’HH:mm:ss:SSS’);
t.Format = ‘HH:mm:ss.SSS’;
Date_Number = datenum(t);
t_plot = datetime(Date_Number, ‘ConvertFrom’, ‘datenum’);
t_plot.Format = ‘HH:mm:ss.SSS’;
%Plotting ECG and PPG Data on the same graph
figure;
plot(t_plot,ECG_Data_normalized, ‘b’, t_plot(ecgPeakIdx), ecgPeaks, ‘ro’, …
t_plot, PPG_Data_normalized, ‘r’, t_plot(ppgPeakIdx), ppgPeaks, ‘go’);
xlabel(‘time’);
ylabel(‘Normalized Data’);
title([‘ECG and PPG Data vs Time – Workbook ‘, num2str(i), ‘sheet’, sheets{j}]);
legend(‘ECG’, ‘ecgPeaks’, ‘PPG’, ‘PPG Peaks’);
% Store the figure handle for later reference if needed
Plotted_Data_ECG_PPG{i,j} = gcf;
Time_Data_Cell = num2cell(Time_Data);
ECG_Data_Cell = num2cell(ECG_Data);
PPG_Data_Cell = num2cell(PPG_Data);
SYS_Data_Cell = num2cell(SYS_Data);
DIA_Data_Cell = num2cell(DIA_Data);
% Place the formatted time data and numerical data in the first row
All_Data{i,j} = [cellstr(Time_Formatted), ECG_Data_Cell, PPG_Data_Cell, SYS_Data_Cell, DIA_Data_Cell];
end
endI’m trying to detect the pulse transit time between ecg and ppg signals. I have the ecg and ppg signals filtered and normalised around 1. Here is my code so far
clc;
clear;
close all;
All_Data = {}; % set up cell array for all workbook data
Plotted_Data_ECG_PPG = {}; % Set up cell array for ECG and PPG plotted data
% Parameters for moving average filter
windowSize = 2;
ecgThreshold = 0.375;
ppgThreshold = 0.1;
for i = 1:1 % set up loop to run for 11 iterations (no. of workbooks)
filename = sprintf(‘%03d.xlsx’, i); % set up each filename 001-011 to be read on each iteration
opt = detectImportOptions(filename); % import data from filename
sheets = sheetnames(filename); % retrieve names of sheets
for j = 1:numel(sheets) % iterate over each sheet within a workbook
tBC = readtable(filename, opt, ‘Sheet’, sheets{j}); % extract sheets from workbooks
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Remove invalid rows from table (corresponding to NaN’s in Time_Data
rows2delete = isnan(Time_Data);
tBC(rows2delete,:) = [];
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Fit a polynomial p of 1st degree to the first points of each staircase (top curve)
xx = (1:numel(Time_Data))’;
dTime_Data = diff(Time_Data);
ind = 1+find(dTime_Data>max(dTime_Data)/100);
ind = ind(2:end); % in some cases the first point is too much off trend and we prefer not to use it.
p = polyfit(xx(ind),Time_Data(ind),1);
% Evaluate the fitted polynomial p and plot:
Time_Data_new = polyval(p,xx);
% % debug plots (to double check)
% figure(j)
% plot(xx,Time_Data,xx,Time_Data_new);
ECG_Data = tBC{:, ‘Var6’}; % extract ECG data from column 6
PPG_Data = tBC{:, ‘Var8’}; % extract PPG data from column 8
SYS_Data = tBC{:, ‘Var10’}; % extract reference systolic pressure data from column 10
DIA_Data = tBC{:, ‘Var12’}; % extract reference diastolic pressure data from column 12
% Filter ECG and PPG data
ECG_Data_smoothed = movmean(ECG_Data, windowSize);
PPG_Data_smoothed = movmean(PPG_Data, windowSize);
% Normalize ECG and PPG data around 0
ECG_Data_normalized = ECG_Data_smoothed – mean(ECG_Data_smoothed);
PPG_Data_normalized = PPG_Data_smoothed – mean(PPG_Data_smoothed);
% Fnd peaks for ECG and PPG data above thresholds
[ecgPeaks, ecgPeakIdx] = findpeaks(ECG_Data_normalized, ‘MinPeakHeight’, ecgThreshold);
[ppgPeaks, ppgPeakIdx] = findpeaks(PPG_Data_normalized, ‘MinPeakHeight’, ppgThreshold);
Time_Formatted = datestr(Time_Data_new, ‘HH:MM:SS:fff’); % Format time data with milliseconds
t = datetime(Time_Formatted,’InputFormat’,’HH:mm:ss:SSS’);
t.Format = ‘HH:mm:ss.SSS’;
Date_Number = datenum(t);
t_plot = datetime(Date_Number, ‘ConvertFrom’, ‘datenum’);
t_plot.Format = ‘HH:mm:ss.SSS’;
%Plotting ECG and PPG Data on the same graph
figure;
plot(t_plot,ECG_Data_normalized, ‘b’, t_plot(ecgPeakIdx), ecgPeaks, ‘ro’, …
t_plot, PPG_Data_normalized, ‘r’, t_plot(ppgPeakIdx), ppgPeaks, ‘go’);
xlabel(‘time’);
ylabel(‘Normalized Data’);
title([‘ECG and PPG Data vs Time – Workbook ‘, num2str(i), ‘sheet’, sheets{j}]);
legend(‘ECG’, ‘ecgPeaks’, ‘PPG’, ‘PPG Peaks’);
% Store the figure handle for later reference if needed
Plotted_Data_ECG_PPG{i,j} = gcf;
Time_Data_Cell = num2cell(Time_Data);
ECG_Data_Cell = num2cell(ECG_Data);
PPG_Data_Cell = num2cell(PPG_Data);
SYS_Data_Cell = num2cell(SYS_Data);
DIA_Data_Cell = num2cell(DIA_Data);
% Place the formatted time data and numerical data in the first row
All_Data{i,j} = [cellstr(Time_Formatted), ECG_Data_Cell, PPG_Data_Cell, SYS_Data_Cell, DIA_Data_Cell];
end
end I’m trying to detect the pulse transit time between ecg and ppg signals. I have the ecg and ppg signals filtered and normalised around 1. Here is my code so far
clc;
clear;
close all;
All_Data = {}; % set up cell array for all workbook data
Plotted_Data_ECG_PPG = {}; % Set up cell array for ECG and PPG plotted data
% Parameters for moving average filter
windowSize = 2;
ecgThreshold = 0.375;
ppgThreshold = 0.1;
for i = 1:1 % set up loop to run for 11 iterations (no. of workbooks)
filename = sprintf(‘%03d.xlsx’, i); % set up each filename 001-011 to be read on each iteration
opt = detectImportOptions(filename); % import data from filename
sheets = sheetnames(filename); % retrieve names of sheets
for j = 1:numel(sheets) % iterate over each sheet within a workbook
tBC = readtable(filename, opt, ‘Sheet’, sheets{j}); % extract sheets from workbooks
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Remove invalid rows from table (corresponding to NaN’s in Time_Data
rows2delete = isnan(Time_Data);
tBC(rows2delete,:) = [];
Time_Data = tBC{:, ‘Var4’}; % extract time data from column 4
% Fit a polynomial p of 1st degree to the first points of each staircase (top curve)
xx = (1:numel(Time_Data))’;
dTime_Data = diff(Time_Data);
ind = 1+find(dTime_Data>max(dTime_Data)/100);
ind = ind(2:end); % in some cases the first point is too much off trend and we prefer not to use it.
p = polyfit(xx(ind),Time_Data(ind),1);
% Evaluate the fitted polynomial p and plot:
Time_Data_new = polyval(p,xx);
% % debug plots (to double check)
% figure(j)
% plot(xx,Time_Data,xx,Time_Data_new);
ECG_Data = tBC{:, ‘Var6’}; % extract ECG data from column 6
PPG_Data = tBC{:, ‘Var8’}; % extract PPG data from column 8
SYS_Data = tBC{:, ‘Var10’}; % extract reference systolic pressure data from column 10
DIA_Data = tBC{:, ‘Var12’}; % extract reference diastolic pressure data from column 12
% Filter ECG and PPG data
ECG_Data_smoothed = movmean(ECG_Data, windowSize);
PPG_Data_smoothed = movmean(PPG_Data, windowSize);
% Normalize ECG and PPG data around 0
ECG_Data_normalized = ECG_Data_smoothed – mean(ECG_Data_smoothed);
PPG_Data_normalized = PPG_Data_smoothed – mean(PPG_Data_smoothed);
% Fnd peaks for ECG and PPG data above thresholds
[ecgPeaks, ecgPeakIdx] = findpeaks(ECG_Data_normalized, ‘MinPeakHeight’, ecgThreshold);
[ppgPeaks, ppgPeakIdx] = findpeaks(PPG_Data_normalized, ‘MinPeakHeight’, ppgThreshold);
Time_Formatted = datestr(Time_Data_new, ‘HH:MM:SS:fff’); % Format time data with milliseconds
t = datetime(Time_Formatted,’InputFormat’,’HH:mm:ss:SSS’);
t.Format = ‘HH:mm:ss.SSS’;
Date_Number = datenum(t);
t_plot = datetime(Date_Number, ‘ConvertFrom’, ‘datenum’);
t_plot.Format = ‘HH:mm:ss.SSS’;
%Plotting ECG and PPG Data on the same graph
figure;
plot(t_plot,ECG_Data_normalized, ‘b’, t_plot(ecgPeakIdx), ecgPeaks, ‘ro’, …
t_plot, PPG_Data_normalized, ‘r’, t_plot(ppgPeakIdx), ppgPeaks, ‘go’);
xlabel(‘time’);
ylabel(‘Normalized Data’);
title([‘ECG and PPG Data vs Time – Workbook ‘, num2str(i), ‘sheet’, sheets{j}]);
legend(‘ECG’, ‘ecgPeaks’, ‘PPG’, ‘PPG Peaks’);
% Store the figure handle for later reference if needed
Plotted_Data_ECG_PPG{i,j} = gcf;
Time_Data_Cell = num2cell(Time_Data);
ECG_Data_Cell = num2cell(ECG_Data);
PPG_Data_Cell = num2cell(PPG_Data);
SYS_Data_Cell = num2cell(SYS_Data);
DIA_Data_Cell = num2cell(DIA_Data);
% Place the formatted time data and numerical data in the first row
All_Data{i,j} = [cellstr(Time_Formatted), ECG_Data_Cell, PPG_Data_Cell, SYS_Data_Cell, DIA_Data_Cell];
end
end ptt, blood pressure MATLAB Answers — New Questions
How do I interpolate and smoothen ndvi time series?
I have ununiformly distributed noisey ndvi time series. I want to interpolate and smoothen it using matlab. I am attaching the sample ndvi file and request you to please suggest me how to achieve it using matlab. I would appreciate your kind cooperation and help.
JyotiI have ununiformly distributed noisey ndvi time series. I want to interpolate and smoothen it using matlab. I am attaching the sample ndvi file and request you to please suggest me how to achieve it using matlab. I would appreciate your kind cooperation and help.
Jyoti I have ununiformly distributed noisey ndvi time series. I want to interpolate and smoothen it using matlab. I am attaching the sample ndvi file and request you to please suggest me how to achieve it using matlab. I would appreciate your kind cooperation and help.
Jyoti how do i interpolate and smoothen ndvi time series MATLAB Answers — New Questions
Create an array of distinct objects of handle class
I want to store objects of a handle class in an array.
When using
for i=1:2
arr(i) = uilabel;
end
arrFor(1).Text = "textFor 1";
arr(2).Text = "textFor 2";
the objects in the array are distinct.
When using
arrDir(1:2) = uilabel;
arrDir(1).Text = "textDir 1";
arrDir(2).Text = "textDir 2";
both text will change to "textDir 2" which makes sense because uilabel is a handle class.
What is the syntax to avoid the for loop and diretly crating an array of distinct objects of a handle class?I want to store objects of a handle class in an array.
When using
for i=1:2
arr(i) = uilabel;
end
arrFor(1).Text = "textFor 1";
arr(2).Text = "textFor 2";
the objects in the array are distinct.
When using
arrDir(1:2) = uilabel;
arrDir(1).Text = "textDir 1";
arrDir(2).Text = "textDir 2";
both text will change to "textDir 2" which makes sense because uilabel is a handle class.
What is the syntax to avoid the for loop and diretly crating an array of distinct objects of a handle class? I want to store objects of a handle class in an array.
When using
for i=1:2
arr(i) = uilabel;
end
arrFor(1).Text = "textFor 1";
arr(2).Text = "textFor 2";
the objects in the array are distinct.
When using
arrDir(1:2) = uilabel;
arrDir(1).Text = "textDir 1";
arrDir(2).Text = "textDir 2";
both text will change to "textDir 2" which makes sense because uilabel is a handle class.
What is the syntax to avoid the for loop and diretly crating an array of distinct objects of a handle class? handles, class, arrays MATLAB Answers — New Questions
Extract a figure from a pdf file
pdfFile = "example.pdf" % String
function extractImagePDF(pdfFile)
import java.io.*
import javax.imageio.ImageIO.*
import org.apache.pdfbox.*
filename = fullfile(pwd,pdfFile);
jFile = File(filename);
document = pdmodel.PDDocument.load(jFile);
catalog = document.getDocumentCatalog();
pages = catalog.getPages();
iter = pages.iterator();
% look for image objects on each page of the PDF
while (iter.hasNext())
page = iter.next();
resources = page.getResources();
pageImages = resources.getXObjectNames;
if ~isempty(pageImages)
imageIter = pageImages.iterator();
i = 1;
% extract each image object from page and write to destination folder
while (imageIter.hasNext())
key = imageIter.next();
if (resources.isImageXObject(key))
xObject = resources.getXObject(key);
img = xObject.getImage();
outputfile = File("Img_"+i +".jpg");
write(img, "jpg", outputfile);
end
i = i+1;
end
end
end
document.close();
endpdfFile = "example.pdf" % String
function extractImagePDF(pdfFile)
import java.io.*
import javax.imageio.ImageIO.*
import org.apache.pdfbox.*
filename = fullfile(pwd,pdfFile);
jFile = File(filename);
document = pdmodel.PDDocument.load(jFile);
catalog = document.getDocumentCatalog();
pages = catalog.getPages();
iter = pages.iterator();
% look for image objects on each page of the PDF
while (iter.hasNext())
page = iter.next();
resources = page.getResources();
pageImages = resources.getXObjectNames;
if ~isempty(pageImages)
imageIter = pageImages.iterator();
i = 1;
% extract each image object from page and write to destination folder
while (imageIter.hasNext())
key = imageIter.next();
if (resources.isImageXObject(key))
xObject = resources.getXObject(key);
img = xObject.getImage();
outputfile = File("Img_"+i +".jpg");
write(img, "jpg", outputfile);
end
i = i+1;
end
end
end
document.close();
end pdfFile = "example.pdf" % String
function extractImagePDF(pdfFile)
import java.io.*
import javax.imageio.ImageIO.*
import org.apache.pdfbox.*
filename = fullfile(pwd,pdfFile);
jFile = File(filename);
document = pdmodel.PDDocument.load(jFile);
catalog = document.getDocumentCatalog();
pages = catalog.getPages();
iter = pages.iterator();
% look for image objects on each page of the PDF
while (iter.hasNext())
page = iter.next();
resources = page.getResources();
pageImages = resources.getXObjectNames;
if ~isempty(pageImages)
imageIter = pageImages.iterator();
i = 1;
% extract each image object from page and write to destination folder
while (imageIter.hasNext())
key = imageIter.next();
if (resources.isImageXObject(key))
xObject = resources.getXObject(key);
img = xObject.getImage();
outputfile = File("Img_"+i +".jpg");
write(img, "jpg", outputfile);
end
i = i+1;
end
end
end
document.close();
end extraction of an image MATLAB Answers — New Questions
Updating channel settings – field descriptions via python
I’m trying to update my channel settings via a PUT request using Python and the Requests library. I’m following the example and guidance that’s shown here: Mathworks-WriteSettings.
Following the example URL as a guide I get a URL parameter string that appears to meet the requirements, however I get the following error mesage: {"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
I have found a couple posts with similar issues and the fix action guidance was to ensure that the channel ID and API write keys are correct and match each other (i.e. the right write key for the right channel). I have double-checked mine a dozen times and I’m successfully sending actual data to the channel using the same key, so I’m pretty confident those parameters are correct.
In the documentation, the example URL is shown in two ways — one way has ".json" appended to the primary URL (before the ? parameters). There’s another example further down the page that shows the URL without .json appended.
If I remove the .json from my request, I do actually get a response that says I’ve successfully updated the channel, such as:
{‘api_key’: ‘<the_actual_api_key’, ‘field1’: ‘Air Temp’, etc……..}
Field names updated successfully!
However, no updates actually appear in the channel settings! As I understand it, the only purpose of the .json tag is to let ThingSpeak know whether to provide its response in json format as opposed to html (which appears to be the default response format).
I can post the entire python code if useful but it mostly it just creates the api_url shown below.
Any and all suggestions welcome — thank you!!
Python code:
% # This passes authentication, returns 200 – but doesn’t effect any actual settings changes…
api_url = ‘https://api.thingspeak.com/channels/2475657?api_key=<actual_key>&field7=AirTemp’
% # This returns 401
api_url = ‘https://api.thingspeak.com/channels/2475657.json?api_key=<actual_key>&field7=AirTemp’I’m trying to update my channel settings via a PUT request using Python and the Requests library. I’m following the example and guidance that’s shown here: Mathworks-WriteSettings.
Following the example URL as a guide I get a URL parameter string that appears to meet the requirements, however I get the following error mesage: {"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
I have found a couple posts with similar issues and the fix action guidance was to ensure that the channel ID and API write keys are correct and match each other (i.e. the right write key for the right channel). I have double-checked mine a dozen times and I’m successfully sending actual data to the channel using the same key, so I’m pretty confident those parameters are correct.
In the documentation, the example URL is shown in two ways — one way has ".json" appended to the primary URL (before the ? parameters). There’s another example further down the page that shows the URL without .json appended.
If I remove the .json from my request, I do actually get a response that says I’ve successfully updated the channel, such as:
{‘api_key’: ‘<the_actual_api_key’, ‘field1’: ‘Air Temp’, etc……..}
Field names updated successfully!
However, no updates actually appear in the channel settings! As I understand it, the only purpose of the .json tag is to let ThingSpeak know whether to provide its response in json format as opposed to html (which appears to be the default response format).
I can post the entire python code if useful but it mostly it just creates the api_url shown below.
Any and all suggestions welcome — thank you!!
Python code:
% # This passes authentication, returns 200 – but doesn’t effect any actual settings changes…
api_url = ‘https://api.thingspeak.com/channels/2475657?api_key=<actual_key>&field7=AirTemp’
% # This returns 401
api_url = ‘https://api.thingspeak.com/channels/2475657.json?api_key=<actual_key>&field7=AirTemp’ I’m trying to update my channel settings via a PUT request using Python and the Requests library. I’m following the example and guidance that’s shown here: Mathworks-WriteSettings.
Following the example URL as a guide I get a URL parameter string that appears to meet the requirements, however I get the following error mesage: {"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
I have found a couple posts with similar issues and the fix action guidance was to ensure that the channel ID and API write keys are correct and match each other (i.e. the right write key for the right channel). I have double-checked mine a dozen times and I’m successfully sending actual data to the channel using the same key, so I’m pretty confident those parameters are correct.
In the documentation, the example URL is shown in two ways — one way has ".json" appended to the primary URL (before the ? parameters). There’s another example further down the page that shows the URL without .json appended.
If I remove the .json from my request, I do actually get a response that says I’ve successfully updated the channel, such as:
{‘api_key’: ‘<the_actual_api_key’, ‘field1’: ‘Air Temp’, etc……..}
Field names updated successfully!
However, no updates actually appear in the channel settings! As I understand it, the only purpose of the .json tag is to let ThingSpeak know whether to provide its response in json format as opposed to html (which appears to be the default response format).
I can post the entire python code if useful but it mostly it just creates the api_url shown below.
Any and all suggestions welcome — thank you!!
Python code:
% # This passes authentication, returns 200 – but doesn’t effect any actual settings changes…
api_url = ‘https://api.thingspeak.com/channels/2475657?api_key=<actual_key>&field7=AirTemp’
% # This returns 401
api_url = ‘https://api.thingspeak.com/channels/2475657.json?api_key=<actual_key>&field7=AirTemp’ write channel settings MATLAB Answers — New Questions
Is it possible to just set the lower limit of the y-axis?
I just want to set the lower limit of the y-axis to zero.
But with ‘ylim’, I have to also set the upper limit, which I do not know what value is appropriate.
What should I do?I just want to set the lower limit of the y-axis to zero.
But with ‘ylim’, I have to also set the upper limit, which I do not know what value is appropriate.
What should I do? I just want to set the lower limit of the y-axis to zero.
But with ‘ylim’, I have to also set the upper limit, which I do not know what value is appropriate.
What should I do? ylim, graphics MATLAB Answers — New Questions
how do I get my license number?
can’t get it, who I need to ask?
I need to download Matlab immediately but need the license numbercan’t get it, who I need to ask?
I need to download Matlab immediately but need the license number can’t get it, who I need to ask?
I need to download Matlab immediately but need the license number license, come on already – it is ver, no need to ask or answer again MATLAB Answers — New Questions
How to flip the x axis in a 3d plot?
Hello Everyone
I need help regarding how to plot the x or y or maybe z axis values in backward mode. Like instead of it starts at 0 it will start at its maximum value and finish at minimum value. It would be best for me to explain with visual demontration.
My Plot:
The plot I want:
In the below image , the x axis starts at 90 and end at 0. I want my x axis to start at 180 and end at 0.
My code:
clc
clear
close all
f=13.56e6; % Fundamental Frequency
T=1/f; % Fundamental Period
omega=2*180*f;
t=0:T*.0001:T;
%************************Triple Fequency Case****************%
k=3; % Number of consecutive Harmonics
Total_Applied_Voltage=300;
V0=(2*Total_Applied_Voltage)/(k+1);
V=nan(1,k);
Omega=nan(1,k);
V_rf=0;
for n=1:1:k
V(n)=V0*(k-n+1)/(k);
Omega(n)=n*omega;
end
theta2=0:5:180;
discharge_symmetry=linspace(0,1,length(theta2));
Dc_Self_Bias = nan(length(theta2), length(discharge_symmetry));
for x=1:1:length(discharge_symmetry)
for y=1:1:length(theta2)
Vrf=V(1)*cosd(Omega(1)*t)+V(2)*cosd(Omega(2)*t+theta2(y))+V(3)*cosd(Omega(3)*t);
Dc_Self_Bias(y,x)=-(((max(Vrf)+(discharge_symmetry(x)*min(Vrf)))/(1+discharge_symmetry(x)))/Total_Applied_Voltage)*100;
end
end
figure(1)
hsc = surfc(theta2, discharge_symmetry, Dc_Self_Bias);
% hsc(1).EdgeColor = ‘interp’; % Surface Plot
hsc(2).EdgeColor = ‘black’;
hsc(2).ZLocation = ‘zmin’; % Contour Plot
hsc(2).FaceColor = ‘flat’;
colormap("turbo");
colorbar
xlabel([‘theta_2 ‘,char(176),”])
ylabel(‘discharge symmetry’)
zlabel(‘Dc Self Bias %’)
title(‘Discharge Characteristics’)
xlim([min(theta2), max(theta2)])
ylim([min(discharge_symmetry), max(discharge_symmetry)])
zlim([min(min(Dc_Self_Bias))-10, 40])
xticks(min(theta2):30:max(theta2))
yticks(min(discharge_symmetry):0.1:max(discharge_symmetry))
pbaspect([1 1 1])
grid on
grid minorHello Everyone
I need help regarding how to plot the x or y or maybe z axis values in backward mode. Like instead of it starts at 0 it will start at its maximum value and finish at minimum value. It would be best for me to explain with visual demontration.
My Plot:
The plot I want:
In the below image , the x axis starts at 90 and end at 0. I want my x axis to start at 180 and end at 0.
My code:
clc
clear
close all
f=13.56e6; % Fundamental Frequency
T=1/f; % Fundamental Period
omega=2*180*f;
t=0:T*.0001:T;
%************************Triple Fequency Case****************%
k=3; % Number of consecutive Harmonics
Total_Applied_Voltage=300;
V0=(2*Total_Applied_Voltage)/(k+1);
V=nan(1,k);
Omega=nan(1,k);
V_rf=0;
for n=1:1:k
V(n)=V0*(k-n+1)/(k);
Omega(n)=n*omega;
end
theta2=0:5:180;
discharge_symmetry=linspace(0,1,length(theta2));
Dc_Self_Bias = nan(length(theta2), length(discharge_symmetry));
for x=1:1:length(discharge_symmetry)
for y=1:1:length(theta2)
Vrf=V(1)*cosd(Omega(1)*t)+V(2)*cosd(Omega(2)*t+theta2(y))+V(3)*cosd(Omega(3)*t);
Dc_Self_Bias(y,x)=-(((max(Vrf)+(discharge_symmetry(x)*min(Vrf)))/(1+discharge_symmetry(x)))/Total_Applied_Voltage)*100;
end
end
figure(1)
hsc = surfc(theta2, discharge_symmetry, Dc_Self_Bias);
% hsc(1).EdgeColor = ‘interp’; % Surface Plot
hsc(2).EdgeColor = ‘black’;
hsc(2).ZLocation = ‘zmin’; % Contour Plot
hsc(2).FaceColor = ‘flat’;
colormap("turbo");
colorbar
xlabel([‘theta_2 ‘,char(176),”])
ylabel(‘discharge symmetry’)
zlabel(‘Dc Self Bias %’)
title(‘Discharge Characteristics’)
xlim([min(theta2), max(theta2)])
ylim([min(discharge_symmetry), max(discharge_symmetry)])
zlim([min(min(Dc_Self_Bias))-10, 40])
xticks(min(theta2):30:max(theta2))
yticks(min(discharge_symmetry):0.1:max(discharge_symmetry))
pbaspect([1 1 1])
grid on
grid minor Hello Everyone
I need help regarding how to plot the x or y or maybe z axis values in backward mode. Like instead of it starts at 0 it will start at its maximum value and finish at minimum value. It would be best for me to explain with visual demontration.
My Plot:
The plot I want:
In the below image , the x axis starts at 90 and end at 0. I want my x axis to start at 180 and end at 0.
My code:
clc
clear
close all
f=13.56e6; % Fundamental Frequency
T=1/f; % Fundamental Period
omega=2*180*f;
t=0:T*.0001:T;
%************************Triple Fequency Case****************%
k=3; % Number of consecutive Harmonics
Total_Applied_Voltage=300;
V0=(2*Total_Applied_Voltage)/(k+1);
V=nan(1,k);
Omega=nan(1,k);
V_rf=0;
for n=1:1:k
V(n)=V0*(k-n+1)/(k);
Omega(n)=n*omega;
end
theta2=0:5:180;
discharge_symmetry=linspace(0,1,length(theta2));
Dc_Self_Bias = nan(length(theta2), length(discharge_symmetry));
for x=1:1:length(discharge_symmetry)
for y=1:1:length(theta2)
Vrf=V(1)*cosd(Omega(1)*t)+V(2)*cosd(Omega(2)*t+theta2(y))+V(3)*cosd(Omega(3)*t);
Dc_Self_Bias(y,x)=-(((max(Vrf)+(discharge_symmetry(x)*min(Vrf)))/(1+discharge_symmetry(x)))/Total_Applied_Voltage)*100;
end
end
figure(1)
hsc = surfc(theta2, discharge_symmetry, Dc_Self_Bias);
% hsc(1).EdgeColor = ‘interp’; % Surface Plot
hsc(2).EdgeColor = ‘black’;
hsc(2).ZLocation = ‘zmin’; % Contour Plot
hsc(2).FaceColor = ‘flat’;
colormap("turbo");
colorbar
xlabel([‘theta_2 ‘,char(176),”])
ylabel(‘discharge symmetry’)
zlabel(‘Dc Self Bias %’)
title(‘Discharge Characteristics’)
xlim([min(theta2), max(theta2)])
ylim([min(discharge_symmetry), max(discharge_symmetry)])
zlim([min(min(Dc_Self_Bias))-10, 40])
xticks(min(theta2):30:max(theta2))
yticks(min(discharge_symmetry):0.1:max(discharge_symmetry))
pbaspect([1 1 1])
grid on
grid minor surface, surf, 3d plots, image analysis MATLAB Answers — New Questions
Getting error while trying to solve boundary condition equations.
I’m currently working on solving a boundary value problem (BVP) represented by a system of ordinary differential equations in MATLAB. However, I’ve encountered some errors during the process, and I’m seeking assistance in resolving them. Below is the code snippet
close all; clear all; clc;
K1=0; eta1=0.2; eta2=0.7; lambda1=0.5; Fr=0.5; Rd=0.5; Sc=0.8; Pr=1; omega=0.5; Nr=0.5; B1=0.5; Nt=0.4; beta1=0.3; m1=0.4; Pe=0.3; E2=0.2; Lb=0.4; Rb=0.6; alpha=0.3; r1=0.3; Kp=0.3;
w=1; Nb=0.5; B2=0.5;
% fprintf(‘Workingn’);
for M1 = 0:0.1:1
V1(w)= M1;
j=1;
% fprintf(‘Workingn’);
% global khp;
% khp =@ (x,y) [y(2);
% y(3);
% (-y(1)*y(3)+(1+Fr)*(y(2)^2)+Kp*y(2)+M1*y(2)-lambda1*(y(5)-Nr*y(8)-Rb*y(11)))/(1+K1-eta1*K1*(y(3)^2));
% y(6);
% -(Pr*y(6)*y(1)+Pr*Nb*y(6)*y(9)+Pr*Nt*((y(6))^2)+alpha*Pr*y(5))/(1+Rd*4/3);
% y(9);
% (Sc*beta1*(((1+y(5)*r1))^M1)*y(8)*exp(-E2/(1+r1*y(5)))-Sc*y(1)*y(9)-(Nt/Nb)*y(7));
% y(12);
% (Pe*(y(11)+omega)*y(10)-y(12)*(Lb*y(1)-Pe*y(9)))];
global khp;
khp =@ (x,y) [y(2);
y(3);
((-y(1)*y(3))+((1+Fr)*(y(2)^2))+(Kp*y(2))+(M1*y(2))-(lambda1*(y(4)-Nr*y(6)-Rb*y(8))))/((1+K1)-(eta1*K1*(y(3)^2)));
y(5);
(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)));
y(7);
(Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)))));
y(9);
(Pe*(y(8)+omega)*((Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3))))))+((y(9))*((Pe*y(6))-(Lb*y(1)))))];
% fprintf(‘Workingn’);
init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0]);
% fprintf(‘Workingn’);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
% fprintf(‘Workingn’);
x=linspace(0,9,100);
y1=deval(sol1,x);
Cf(w,j)= ((1+K1)*y1(3,1)-((K1*eta1)/3)*y1(3,1)^(3));
Nu(w,j)=-(1+Rd*4/3)*y1(5,1);
Sh(w,j)=-(y1(7,1));
Nn(w,j)=-(y1(9,1));
w=w+1;
end
%
M1 = 0:0.1:1;
plot(M1,Cf)
function res = bc_bvp(yl,yr) % boundary conditions
eta1=0.2; eta2=0.7;K1=0;B1=0.5; B2=0.5;
%global khp;
%init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0, 0,0,0]);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
%y1=deval(sol1,x);
% fprintf("%fn",length(yr));
%fprintf("%fn",yr(11));
res=[yl(1); yl(2)-1-(eta2)*((1+K1)*yl(3)-(eta1)*K1*(yl(3)^3)); yl(5)+B1*(1-yl(4)); yl(7)+B2*(1-yl(6)); yl(9)-1; yr(2); yr(4); yr(6); yr(9);];
% fprintf("%fn",length(res));
end
looking for some guidance or suggestions .I’m currently working on solving a boundary value problem (BVP) represented by a system of ordinary differential equations in MATLAB. However, I’ve encountered some errors during the process, and I’m seeking assistance in resolving them. Below is the code snippet
close all; clear all; clc;
K1=0; eta1=0.2; eta2=0.7; lambda1=0.5; Fr=0.5; Rd=0.5; Sc=0.8; Pr=1; omega=0.5; Nr=0.5; B1=0.5; Nt=0.4; beta1=0.3; m1=0.4; Pe=0.3; E2=0.2; Lb=0.4; Rb=0.6; alpha=0.3; r1=0.3; Kp=0.3;
w=1; Nb=0.5; B2=0.5;
% fprintf(‘Workingn’);
for M1 = 0:0.1:1
V1(w)= M1;
j=1;
% fprintf(‘Workingn’);
% global khp;
% khp =@ (x,y) [y(2);
% y(3);
% (-y(1)*y(3)+(1+Fr)*(y(2)^2)+Kp*y(2)+M1*y(2)-lambda1*(y(5)-Nr*y(8)-Rb*y(11)))/(1+K1-eta1*K1*(y(3)^2));
% y(6);
% -(Pr*y(6)*y(1)+Pr*Nb*y(6)*y(9)+Pr*Nt*((y(6))^2)+alpha*Pr*y(5))/(1+Rd*4/3);
% y(9);
% (Sc*beta1*(((1+y(5)*r1))^M1)*y(8)*exp(-E2/(1+r1*y(5)))-Sc*y(1)*y(9)-(Nt/Nb)*y(7));
% y(12);
% (Pe*(y(11)+omega)*y(10)-y(12)*(Lb*y(1)-Pe*y(9)))];
global khp;
khp =@ (x,y) [y(2);
y(3);
((-y(1)*y(3))+((1+Fr)*(y(2)^2))+(Kp*y(2))+(M1*y(2))-(lambda1*(y(4)-Nr*y(6)-Rb*y(8))))/((1+K1)-(eta1*K1*(y(3)^2)));
y(5);
(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)));
y(7);
(Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)))));
y(9);
(Pe*(y(8)+omega)*((Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3))))))+((y(9))*((Pe*y(6))-(Lb*y(1)))))];
% fprintf(‘Workingn’);
init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0]);
% fprintf(‘Workingn’);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
% fprintf(‘Workingn’);
x=linspace(0,9,100);
y1=deval(sol1,x);
Cf(w,j)= ((1+K1)*y1(3,1)-((K1*eta1)/3)*y1(3,1)^(3));
Nu(w,j)=-(1+Rd*4/3)*y1(5,1);
Sh(w,j)=-(y1(7,1));
Nn(w,j)=-(y1(9,1));
w=w+1;
end
%
M1 = 0:0.1:1;
plot(M1,Cf)
function res = bc_bvp(yl,yr) % boundary conditions
eta1=0.2; eta2=0.7;K1=0;B1=0.5; B2=0.5;
%global khp;
%init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0, 0,0,0]);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
%y1=deval(sol1,x);
% fprintf("%fn",length(yr));
%fprintf("%fn",yr(11));
res=[yl(1); yl(2)-1-(eta2)*((1+K1)*yl(3)-(eta1)*K1*(yl(3)^3)); yl(5)+B1*(1-yl(4)); yl(7)+B2*(1-yl(6)); yl(9)-1; yr(2); yr(4); yr(6); yr(9);];
% fprintf("%fn",length(res));
end
looking for some guidance or suggestions . I’m currently working on solving a boundary value problem (BVP) represented by a system of ordinary differential equations in MATLAB. However, I’ve encountered some errors during the process, and I’m seeking assistance in resolving them. Below is the code snippet
close all; clear all; clc;
K1=0; eta1=0.2; eta2=0.7; lambda1=0.5; Fr=0.5; Rd=0.5; Sc=0.8; Pr=1; omega=0.5; Nr=0.5; B1=0.5; Nt=0.4; beta1=0.3; m1=0.4; Pe=0.3; E2=0.2; Lb=0.4; Rb=0.6; alpha=0.3; r1=0.3; Kp=0.3;
w=1; Nb=0.5; B2=0.5;
% fprintf(‘Workingn’);
for M1 = 0:0.1:1
V1(w)= M1;
j=1;
% fprintf(‘Workingn’);
% global khp;
% khp =@ (x,y) [y(2);
% y(3);
% (-y(1)*y(3)+(1+Fr)*(y(2)^2)+Kp*y(2)+M1*y(2)-lambda1*(y(5)-Nr*y(8)-Rb*y(11)))/(1+K1-eta1*K1*(y(3)^2));
% y(6);
% -(Pr*y(6)*y(1)+Pr*Nb*y(6)*y(9)+Pr*Nt*((y(6))^2)+alpha*Pr*y(5))/(1+Rd*4/3);
% y(9);
% (Sc*beta1*(((1+y(5)*r1))^M1)*y(8)*exp(-E2/(1+r1*y(5)))-Sc*y(1)*y(9)-(Nt/Nb)*y(7));
% y(12);
% (Pe*(y(11)+omega)*y(10)-y(12)*(Lb*y(1)-Pe*y(9)))];
global khp;
khp =@ (x,y) [y(2);
y(3);
((-y(1)*y(3))+((1+Fr)*(y(2)^2))+(Kp*y(2))+(M1*y(2))-(lambda1*(y(4)-Nr*y(6)-Rb*y(8))))/((1+K1)-(eta1*K1*(y(3)^2)));
y(5);
(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)));
y(7);
(Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3)))));
y(9);
(Pe*(y(8)+omega)*((Sc*beta1*(((1+(y(4)*r1)))^m1)*y(6)*exp(-E2/(1+(r1*y(4))))-(Sc*y(1)*y(7))-((Nt/Nb)*(-((Pr*y(5)*y(1))+(Pr*Nb*y(5)*y(7))+(Pr*Nt*((y(5))^2))+(alpha*Pr*y(4)))/(1+(Rd*4/3))))))+((y(9))*((Pe*y(6))-(Lb*y(1)))))];
% fprintf(‘Workingn’);
init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0]);
% fprintf(‘Workingn’);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
% fprintf(‘Workingn’);
x=linspace(0,9,100);
y1=deval(sol1,x);
Cf(w,j)= ((1+K1)*y1(3,1)-((K1*eta1)/3)*y1(3,1)^(3));
Nu(w,j)=-(1+Rd*4/3)*y1(5,1);
Sh(w,j)=-(y1(7,1));
Nn(w,j)=-(y1(9,1));
w=w+1;
end
%
M1 = 0:0.1:1;
plot(M1,Cf)
function res = bc_bvp(yl,yr) % boundary conditions
eta1=0.2; eta2=0.7;K1=0;B1=0.5; B2=0.5;
%global khp;
%init=bvpinit(linspace(0,9,100),[1/2, 0, 0, 1, 0, 0, 1, 0, 0, 0,0,0]);
bc_output = bc_bvp(sol1);
sol1=bvp4c(khp,bc_output,init);
%y1=deval(sol1,x);
% fprintf("%fn",length(yr));
%fprintf("%fn",yr(11));
res=[yl(1); yl(2)-1-(eta2)*((1+K1)*yl(3)-(eta1)*K1*(yl(3)^3)); yl(5)+B1*(1-yl(4)); yl(7)+B2*(1-yl(6)); yl(9)-1; yr(2); yr(4); yr(6); yr(9);];
% fprintf("%fn",length(res));
end
looking for some guidance or suggestions . matlab, mathematics MATLAB Answers — New Questions
How to remove/identify warnings of Aspen HYSYS through MatLAB
I am currently trying to link hysys and matlab.
All other things I have done, however, treating warnings is my only left part I couldn’t do by activeX handle.
Does anyone know which object specifies warning popups?
In detail, I have troublesome in running a column by function Run(object.ColumnFlowsheet). It shows popups which disables all further codes.
Thanks.I am currently trying to link hysys and matlab.
All other things I have done, however, treating warnings is my only left part I couldn’t do by activeX handle.
Does anyone know which object specifies warning popups?
In detail, I have troublesome in running a column by function Run(object.ColumnFlowsheet). It shows popups which disables all further codes.
Thanks. I am currently trying to link hysys and matlab.
All other things I have done, however, treating warnings is my only left part I couldn’t do by activeX handle.
Does anyone know which object specifies warning popups?
In detail, I have troublesome in running a column by function Run(object.ColumnFlowsheet). It shows popups which disables all further codes.
Thanks. hysys, automation MATLAB Answers — New Questions
Error while calling a Keras Model from Matlab
Basically, I have regression neural network saved in .H5 format. I want to use the NN model’s prediction in my simulink model. I am trying to call the python where the NN model is imported using Keras.load_model. When I call the python with NN model imported I am getting an error but if I call it without the NN model its working fine.
Matlab function to call python:
function y = fcn(in1,in2)
y = 0; % Has to be preassigned, otherwise Simulink throws an error
coder.extrinsic(‘py.final10.test’) % Python functions have to be run extrinsically, meaning no C code generated
y = double(py.final10.test(in1,in2));
end
Python :final10.py
from tensorflow import keras
from keras.models import load_model
import numpy as np
model = load_model(‘model.h5’)
def test(in1,in2):
x1 = in1
x2 = in2
a = np.asarray(x1)
b = np.asarray(x2)
G = np.asarray([a,b])
x3 = G.reshape(1,2)
x4 = model.predict(x3)
print(x4)
y = x1+x2;
return y
If I didn’t include the load_model line, I am able to call the python from Matlab. Can anyone help me to solve this issue.
Below is the error, I am getting:
Undefined function ‘py.finalv10.test’ for input arguments of type ‘double’. Error in ‘active_vehicleV1/Vehicle/MATLAB Function’ (line 4) y = double(py.finalv10.test(in1,in2));Basically, I have regression neural network saved in .H5 format. I want to use the NN model’s prediction in my simulink model. I am trying to call the python where the NN model is imported using Keras.load_model. When I call the python with NN model imported I am getting an error but if I call it without the NN model its working fine.
Matlab function to call python:
function y = fcn(in1,in2)
y = 0; % Has to be preassigned, otherwise Simulink throws an error
coder.extrinsic(‘py.final10.test’) % Python functions have to be run extrinsically, meaning no C code generated
y = double(py.final10.test(in1,in2));
end
Python :final10.py
from tensorflow import keras
from keras.models import load_model
import numpy as np
model = load_model(‘model.h5’)
def test(in1,in2):
x1 = in1
x2 = in2
a = np.asarray(x1)
b = np.asarray(x2)
G = np.asarray([a,b])
x3 = G.reshape(1,2)
x4 = model.predict(x3)
print(x4)
y = x1+x2;
return y
If I didn’t include the load_model line, I am able to call the python from Matlab. Can anyone help me to solve this issue.
Below is the error, I am getting:
Undefined function ‘py.finalv10.test’ for input arguments of type ‘double’. Error in ‘active_vehicleV1/Vehicle/MATLAB Function’ (line 4) y = double(py.finalv10.test(in1,in2)); Basically, I have regression neural network saved in .H5 format. I want to use the NN model’s prediction in my simulink model. I am trying to call the python where the NN model is imported using Keras.load_model. When I call the python with NN model imported I am getting an error but if I call it without the NN model its working fine.
Matlab function to call python:
function y = fcn(in1,in2)
y = 0; % Has to be preassigned, otherwise Simulink throws an error
coder.extrinsic(‘py.final10.test’) % Python functions have to be run extrinsically, meaning no C code generated
y = double(py.final10.test(in1,in2));
end
Python :final10.py
from tensorflow import keras
from keras.models import load_model
import numpy as np
model = load_model(‘model.h5’)
def test(in1,in2):
x1 = in1
x2 = in2
a = np.asarray(x1)
b = np.asarray(x2)
G = np.asarray([a,b])
x3 = G.reshape(1,2)
x4 = model.predict(x3)
print(x4)
y = x1+x2;
return y
If I didn’t include the load_model line, I am able to call the python from Matlab. Can anyone help me to solve this issue.
Below is the error, I am getting:
Undefined function ‘py.finalv10.test’ for input arguments of type ‘double’. Error in ‘active_vehicleV1/Vehicle/MATLAB Function’ (line 4) y = double(py.finalv10.test(in1,in2)); python MATLAB Answers — New Questions
Convert Simulink to m file
A lot (or most or all?) of the configuration of a simulink file can be done programmatically. Is there a way to convert an existing simulink slx file into an m file that contains all (important) steps necessary to build the slx file? I do not care so much about the visual documentation that the simulink file inherently comes with (routing of signals, position of blocks). So, an m file containing all commands to build an slx file is enough for me. The advantage would be that one can more easily track the text-based m file in programs like git (I am aware that there are ways to track simulink files as well but I prefer text-based files).A lot (or most or all?) of the configuration of a simulink file can be done programmatically. Is there a way to convert an existing simulink slx file into an m file that contains all (important) steps necessary to build the slx file? I do not care so much about the visual documentation that the simulink file inherently comes with (routing of signals, position of blocks). So, an m file containing all commands to build an slx file is enough for me. The advantage would be that one can more easily track the text-based m file in programs like git (I am aware that there are ways to track simulink files as well but I prefer text-based files). A lot (or most or all?) of the configuration of a simulink file can be done programmatically. Is there a way to convert an existing simulink slx file into an m file that contains all (important) steps necessary to build the slx file? I do not care so much about the visual documentation that the simulink file inherently comes with (routing of signals, position of blocks). So, an m file containing all commands to build an slx file is enough for me. The advantage would be that one can more easily track the text-based m file in programs like git (I am aware that there are ways to track simulink files as well but I prefer text-based files). simulink, convert, text file MATLAB Answers — New Questions
Acquire data from a python device in continuous (synchronuous) mode on a PC with Matlab installed.
Hi.
I’ve a raspberry device on wich I’ve installed Python.
My raspberry reads in realtime data from an MLX 90640 IR Thermal Camera and write it on a txt file.
If I copy this txt file on a PC with Matlab installed, I can read thermal data and process it in Matlab to produce, i.e., an heatmap.
This process, however, is an asynchronous process since I must :
acquire thermal data on raspberry
stop the acquisition
copy the data on the PC with Matlab installed
run the matlab application to view the heatmap
Obviuosly I’d like to trasforf this process from asynchronous to synchronous so that I can view real time data acquired from raspberry-Python device on Matlab in the same time that they are acquired and in contunuous mode.
The question is: is there any way to do this? And if yes, how?
Any idea?
Thanks in advanceHi.
I’ve a raspberry device on wich I’ve installed Python.
My raspberry reads in realtime data from an MLX 90640 IR Thermal Camera and write it on a txt file.
If I copy this txt file on a PC with Matlab installed, I can read thermal data and process it in Matlab to produce, i.e., an heatmap.
This process, however, is an asynchronous process since I must :
acquire thermal data on raspberry
stop the acquisition
copy the data on the PC with Matlab installed
run the matlab application to view the heatmap
Obviuosly I’d like to trasforf this process from asynchronous to synchronous so that I can view real time data acquired from raspberry-Python device on Matlab in the same time that they are acquired and in contunuous mode.
The question is: is there any way to do this? And if yes, how?
Any idea?
Thanks in advance Hi.
I’ve a raspberry device on wich I’ve installed Python.
My raspberry reads in realtime data from an MLX 90640 IR Thermal Camera and write it on a txt file.
If I copy this txt file on a PC with Matlab installed, I can read thermal data and process it in Matlab to produce, i.e., an heatmap.
This process, however, is an asynchronous process since I must :
acquire thermal data on raspberry
stop the acquisition
copy the data on the PC with Matlab installed
run the matlab application to view the heatmap
Obviuosly I’d like to trasforf this process from asynchronous to synchronous so that I can view real time data acquired from raspberry-Python device on Matlab in the same time that they are acquired and in contunuous mode.
The question is: is there any way to do this? And if yes, how?
Any idea?
Thanks in advance raspberry, phython MATLAB Answers — New Questions
What is algorithm of Support vector parameter optimization
How to find the parameter such cost function, epsilon and gamma in epsilon-SVRHow to find the parameter such cost function, epsilon and gamma in epsilon-SVR How to find the parameter such cost function, epsilon and gamma in epsilon-SVR svr, matalb, machine learning MATLAB Answers — New Questions
Why does this code give error?
clear;clc
%%
fc = 3e8;% Carrier frequency
Nb = 1000;% Number of snapshots
c = 3e8;
wavelength = c/fc;% The wavelength of the received signal
d = 0.5*wavelength;
theta = [5 40];
M = length(theta);% Number of signals
N = 10;% Number of antennas
% Wavenumber
beta = 2*pi/wavelength;
% Signal amplitude
A = 1;
% SNR (dB)
snr = 5;
% Variance of noise
sigma=sqrt((A^2)/(2*10^(snr/10)));
% Source signal
D = randi(M,Nb,1);
S =A*(2*D – 1);
% The electrical phase shift from element to element along the array
phi=beta*d*cos(theta*pi/180);
% Matrix of steering vectors
for i=1:M
for k=1:N;
VecteurDirectionnel(k,i)= exp(j*(k-1)*phi(i));
end
end
% White Gaussien noise
B = (sigma^2)*(randn(N,Nb)+j*randn(N,Nb))/sqrt(2);
% Array output:signal plus noise
X = VecteurDirectionnel*S+B;
% Estimation of the spatial correlation matrix of the observed signal
Rxx = X*X’/Nb;
% Eigen decomposition
[Vi,Li] = eig(Rxx);
[L,I] = sort(diag(Li),’descend’);
V = Vi(:,I);
Vs = V(:,1:M);
Vs1=Vs(1:N-1,:);
Vs2=Vs(2:N,:);
% Direction Of Arrival
% Least square
xsi=linsolve(Vs(1:N-1,:),Vs(2:N,:));
% DOA estimation
doa=acosd((angle(eig(xsi))/(2*pi*d)))clear;clc
%%
fc = 3e8;% Carrier frequency
Nb = 1000;% Number of snapshots
c = 3e8;
wavelength = c/fc;% The wavelength of the received signal
d = 0.5*wavelength;
theta = [5 40];
M = length(theta);% Number of signals
N = 10;% Number of antennas
% Wavenumber
beta = 2*pi/wavelength;
% Signal amplitude
A = 1;
% SNR (dB)
snr = 5;
% Variance of noise
sigma=sqrt((A^2)/(2*10^(snr/10)));
% Source signal
D = randi(M,Nb,1);
S =A*(2*D – 1);
% The electrical phase shift from element to element along the array
phi=beta*d*cos(theta*pi/180);
% Matrix of steering vectors
for i=1:M
for k=1:N;
VecteurDirectionnel(k,i)= exp(j*(k-1)*phi(i));
end
end
% White Gaussien noise
B = (sigma^2)*(randn(N,Nb)+j*randn(N,Nb))/sqrt(2);
% Array output:signal plus noise
X = VecteurDirectionnel*S+B;
% Estimation of the spatial correlation matrix of the observed signal
Rxx = X*X’/Nb;
% Eigen decomposition
[Vi,Li] = eig(Rxx);
[L,I] = sort(diag(Li),’descend’);
V = Vi(:,I);
Vs = V(:,1:M);
Vs1=Vs(1:N-1,:);
Vs2=Vs(2:N,:);
% Direction Of Arrival
% Least square
xsi=linsolve(Vs(1:N-1,:),Vs(2:N,:));
% DOA estimation
doa=acosd((angle(eig(xsi))/(2*pi*d))) clear;clc
%%
fc = 3e8;% Carrier frequency
Nb = 1000;% Number of snapshots
c = 3e8;
wavelength = c/fc;% The wavelength of the received signal
d = 0.5*wavelength;
theta = [5 40];
M = length(theta);% Number of signals
N = 10;% Number of antennas
% Wavenumber
beta = 2*pi/wavelength;
% Signal amplitude
A = 1;
% SNR (dB)
snr = 5;
% Variance of noise
sigma=sqrt((A^2)/(2*10^(snr/10)));
% Source signal
D = randi(M,Nb,1);
S =A*(2*D – 1);
% The electrical phase shift from element to element along the array
phi=beta*d*cos(theta*pi/180);
% Matrix of steering vectors
for i=1:M
for k=1:N;
VecteurDirectionnel(k,i)= exp(j*(k-1)*phi(i));
end
end
% White Gaussien noise
B = (sigma^2)*(randn(N,Nb)+j*randn(N,Nb))/sqrt(2);
% Array output:signal plus noise
X = VecteurDirectionnel*S+B;
% Estimation of the spatial correlation matrix of the observed signal
Rxx = X*X’/Nb;
% Eigen decomposition
[Vi,Li] = eig(Rxx);
[L,I] = sort(diag(Li),’descend’);
V = Vi(:,I);
Vs = V(:,1:M);
Vs1=Vs(1:N-1,:);
Vs2=Vs(2:N,:);
% Direction Of Arrival
% Least square
xsi=linsolve(Vs(1:N-1,:),Vs(2:N,:));
% DOA estimation
doa=acosd((angle(eig(xsi))/(2*pi*d))) why error MATLAB Answers — New Questions
How to determe the Fatigue Damage according Miner’s Rule via rainflow counting
Dear Matlab Users,
I have difficulties calculating the total accumulated fatique damage for a set of data (see Attachements). I have determined the histogram based on Rainflow counting, and determined the line for the SN-curve (maximum allowable stress per cycle). The SN-curve has only one slope in this case.
To calculate the total accumulated fatique damage according Miner’s Rule, the number of cycles of the SN curve should be divided by the number of cycles of the histogram per stress range, and then be summed up.
My question is: How do I divide the values from the number of cycles of the SN-curve by the the values from the number of cycles of the histogram? How do I make the values of the same size? I want to divide the following (see script for clarification):
N=10.^(L_a1-m1*log(cigma_delta*(T/T_ref)^k)); with cigma_delta= [0:0.05:710]; % N-cycles SN-curve
by
C_7=histogram(‘BinEdges’,edges’,’BinCounts’,sum(hist,2), Orientation=’horizontal’) % Rainflow counting histogram
Thanks in advance!Dear Matlab Users,
I have difficulties calculating the total accumulated fatique damage for a set of data (see Attachements). I have determined the histogram based on Rainflow counting, and determined the line for the SN-curve (maximum allowable stress per cycle). The SN-curve has only one slope in this case.
To calculate the total accumulated fatique damage according Miner’s Rule, the number of cycles of the SN curve should be divided by the number of cycles of the histogram per stress range, and then be summed up.
My question is: How do I divide the values from the number of cycles of the SN-curve by the the values from the number of cycles of the histogram? How do I make the values of the same size? I want to divide the following (see script for clarification):
N=10.^(L_a1-m1*log(cigma_delta*(T/T_ref)^k)); with cigma_delta= [0:0.05:710]; % N-cycles SN-curve
by
C_7=histogram(‘BinEdges’,edges’,’BinCounts’,sum(hist,2), Orientation=’horizontal’) % Rainflow counting histogram
Thanks in advance! Dear Matlab Users,
I have difficulties calculating the total accumulated fatique damage for a set of data (see Attachements). I have determined the histogram based on Rainflow counting, and determined the line for the SN-curve (maximum allowable stress per cycle). The SN-curve has only one slope in this case.
To calculate the total accumulated fatique damage according Miner’s Rule, the number of cycles of the SN curve should be divided by the number of cycles of the histogram per stress range, and then be summed up.
My question is: How do I divide the values from the number of cycles of the SN-curve by the the values from the number of cycles of the histogram? How do I make the values of the same size? I want to divide the following (see script for clarification):
N=10.^(L_a1-m1*log(cigma_delta*(T/T_ref)^k)); with cigma_delta= [0:0.05:710]; % N-cycles SN-curve
by
C_7=histogram(‘BinEdges’,edges’,’BinCounts’,sum(hist,2), Orientation=’horizontal’) % Rainflow counting histogram
Thanks in advance! rainflow counting, miner’s rule, histogram, sn-curve, fatigue MATLAB Answers — New Questions