Tag Archives: matlab
Documentation for HDL code generated
Is there any way i generate documentation or comments along with the hdl code using hdl coder?Is there any way i generate documentation or comments along with the hdl code using hdl coder? Is there any way i generate documentation or comments along with the hdl code using hdl coder? hdlcoder, dsp hdl toolbox, hdlverifier MATLAB Answers — New Questions
fail to start parallel pool
picturepicture picture transferred MATLAB Answers — New Questions
i would like to know why my code doesn’t work please, the data load factors is supposed to be taken from a .txt file from DASL website
function load_factors_analysis()
% Load the data (assuming ‘load_factors.csv’ is in the working directory)
data = load(‘load_factors.csv’);
% Get central and dispersion measurements for each variable
[mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data);
% Create histograms and/or bar graphs for each variable
histograms_and_bar_graphs(data);
% Create a boxplot (assuming data(:,1) is continuous and data(:,2) is categorical)
boxplot_categorical(data(:, 1), data(:, 2));
% Perform a regression analysis (assuming data(:,1) and data(:,2) are continuous)
regression_analysis(data(:, 1), data(:, 2));
% Discuss the results (replace with your actual analysis)
discussion(data, mean, median, stddev, min_val, max_val);
end
function [mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data)
% Get central and dispersion statistics
mean = mean(data);
median = median(data);
stddev = std(data);
min_val = min(data);
max_val = max(data);
% Return the calculated values
return (mean, median; stddev; min_val; max_val);
end
function histograms_and_bar_graphs(data)
for i = 1:size(data, 2)
if isnumeric(data(:, i))
h = histogram(data(:, i));
title(strcat(‘Histogram of ‘, data(1, i)));
show(h);
else
b = bar(unique(data(:, i)), count(data(:, i)));
title(strcat(‘Bar graph of ‘, data(1, i)));
show(b);
end
end
end
function boxplot_categorical(data_continuous, data_categorical)
% Create a boxplot for continuous data divided by categorical classes
boxplot(data_continuous, data_categorical);
end
function regression_analysis(data1, data2)
% Perform linear regression
[b, a, rsq, pval, se] = regress(data1, data2);
% Print the results
disp(‘Coefficients:’);
disp([b, a]);
disp(‘R-squared:’);
disp(rsq);
disp(‘P-value:’);
disp(pval);
disp(‘Standard error:’);
disp(se);
end
function discussion(~, ~, ~, ~, ~, ~)
% Replace this with your analysis of the data and calculated statistics
disp(‘This is a placeholder for your data analysis discussion.’);
disp(‘Here, you would discuss insights from the central tendency’);
disp(‘(mean, median), dispersion (standard deviation),’);
disp(‘minimum and maximum values, and any relationships found’);
disp(‘between variables using the boxplot and regression analysis.’);
endfunction load_factors_analysis()
% Load the data (assuming ‘load_factors.csv’ is in the working directory)
data = load(‘load_factors.csv’);
% Get central and dispersion measurements for each variable
[mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data);
% Create histograms and/or bar graphs for each variable
histograms_and_bar_graphs(data);
% Create a boxplot (assuming data(:,1) is continuous and data(:,2) is categorical)
boxplot_categorical(data(:, 1), data(:, 2));
% Perform a regression analysis (assuming data(:,1) and data(:,2) are continuous)
regression_analysis(data(:, 1), data(:, 2));
% Discuss the results (replace with your actual analysis)
discussion(data, mean, median, stddev, min_val, max_val);
end
function [mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data)
% Get central and dispersion statistics
mean = mean(data);
median = median(data);
stddev = std(data);
min_val = min(data);
max_val = max(data);
% Return the calculated values
return (mean, median; stddev; min_val; max_val);
end
function histograms_and_bar_graphs(data)
for i = 1:size(data, 2)
if isnumeric(data(:, i))
h = histogram(data(:, i));
title(strcat(‘Histogram of ‘, data(1, i)));
show(h);
else
b = bar(unique(data(:, i)), count(data(:, i)));
title(strcat(‘Bar graph of ‘, data(1, i)));
show(b);
end
end
end
function boxplot_categorical(data_continuous, data_categorical)
% Create a boxplot for continuous data divided by categorical classes
boxplot(data_continuous, data_categorical);
end
function regression_analysis(data1, data2)
% Perform linear regression
[b, a, rsq, pval, se] = regress(data1, data2);
% Print the results
disp(‘Coefficients:’);
disp([b, a]);
disp(‘R-squared:’);
disp(rsq);
disp(‘P-value:’);
disp(pval);
disp(‘Standard error:’);
disp(se);
end
function discussion(~, ~, ~, ~, ~, ~)
% Replace this with your analysis of the data and calculated statistics
disp(‘This is a placeholder for your data analysis discussion.’);
disp(‘Here, you would discuss insights from the central tendency’);
disp(‘(mean, median), dispersion (standard deviation),’);
disp(‘minimum and maximum values, and any relationships found’);
disp(‘between variables using the boxplot and regression analysis.’);
end function load_factors_analysis()
% Load the data (assuming ‘load_factors.csv’ is in the working directory)
data = load(‘load_factors.csv’);
% Get central and dispersion measurements for each variable
[mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data);
% Create histograms and/or bar graphs for each variable
histograms_and_bar_graphs(data);
% Create a boxplot (assuming data(:,1) is continuous and data(:,2) is categorical)
boxplot_categorical(data(:, 1), data(:, 2));
% Perform a regression analysis (assuming data(:,1) and data(:,2) are continuous)
regression_analysis(data(:, 1), data(:, 2));
% Discuss the results (replace with your actual analysis)
discussion(data, mean, median, stddev, min_val, max_val);
end
function [mean, median, stddev, min_val, max_val] = central_dispersion_measurements(data)
% Get central and dispersion statistics
mean = mean(data);
median = median(data);
stddev = std(data);
min_val = min(data);
max_val = max(data);
% Return the calculated values
return (mean, median; stddev; min_val; max_val);
end
function histograms_and_bar_graphs(data)
for i = 1:size(data, 2)
if isnumeric(data(:, i))
h = histogram(data(:, i));
title(strcat(‘Histogram of ‘, data(1, i)));
show(h);
else
b = bar(unique(data(:, i)), count(data(:, i)));
title(strcat(‘Bar graph of ‘, data(1, i)));
show(b);
end
end
end
function boxplot_categorical(data_continuous, data_categorical)
% Create a boxplot for continuous data divided by categorical classes
boxplot(data_continuous, data_categorical);
end
function regression_analysis(data1, data2)
% Perform linear regression
[b, a, rsq, pval, se] = regress(data1, data2);
% Print the results
disp(‘Coefficients:’);
disp([b, a]);
disp(‘R-squared:’);
disp(rsq);
disp(‘P-value:’);
disp(pval);
disp(‘Standard error:’);
disp(se);
end
function discussion(~, ~, ~, ~, ~, ~)
% Replace this with your analysis of the data and calculated statistics
disp(‘This is a placeholder for your data analysis discussion.’);
disp(‘Here, you would discuss insights from the central tendency’);
disp(‘(mean, median), dispersion (standard deviation),’);
disp(‘minimum and maximum values, and any relationships found’);
disp(‘between variables using the boxplot and regression analysis.’);
end statistics, code issues MATLAB Answers — New Questions
Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
[app.Sis.Slippage]
ans =
Columns 1 through 17
0 9 9 9 6 9 6 6 6 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
b1 =
Columns 1 through 17
0 90 90 90 60 90 60 60 60 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
[app.Sis.Slippage]=b1
Insufficient number of outputs from right hand side of equal sign to satisfy assignment.[app.Sis.Slippage]
ans =
Columns 1 through 17
0 9 9 9 6 9 6 6 6 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
b1 =
Columns 1 through 17
0 90 90 90 60 90 60 60 60 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
[app.Sis.Slippage]=b1
Insufficient number of outputs from right hand side of equal sign to satisfy assignment. [app.Sis.Slippage]
ans =
Columns 1 through 17
0 9 9 9 6 9 6 6 6 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
b1 =
Columns 1 through 17
0 90 90 90 60 90 60 60 60 0 0 0 0 0 0 0 0
Columns 18 through 34
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Column 35
0
[app.Sis.Slippage]=b1
Insufficient number of outputs from right hand side of equal sign to satisfy assignment. insufficient number of outputs from right hand sid MATLAB Answers — New Questions
Error when click “Send to simulink” Button on Bikesim
When click "Send to simulink" Button on Bikesim, i receive and signal like this. How can I solve this problem?
Thanks for your helps.When click "Send to simulink" Button on Bikesim, i receive and signal like this. How can I solve this problem?
Thanks for your helps. When click "Send to simulink" Button on Bikesim, i receive and signal like this. How can I solve this problem?
Thanks for your helps. bikesim, cannot find matlab MATLAB Answers — New Questions
multiplying polynomials with conv
use matlab to carry out the following multiplication of polynomials
(x+1.4)(x-0.4)x(x+0.6)(x-1.4)
heres what i did—
a = [1,1.4];
b = [1, -.4];
c = [1, 0];
d = [1, .6];
e = [1, -1.4];
p = conv(a, conv(b, conv(c, conv(d, e))))
it gave me the correct result but its tagging an extra zero onto the end of my result. i assume this means its coming out as one higher power then it is supposed to be with a "0" constant. anyone see any problems here?
my answer is supposed to come out as
p = [1, 0.2, -2.2, -3.92, .4704]
while my work is giving me
p = [1, 0.2, -2.2, -3.92, .4704, 0]
so somewhere it is giving me an extra power of x and im not sure whyuse matlab to carry out the following multiplication of polynomials
(x+1.4)(x-0.4)x(x+0.6)(x-1.4)
heres what i did—
a = [1,1.4];
b = [1, -.4];
c = [1, 0];
d = [1, .6];
e = [1, -1.4];
p = conv(a, conv(b, conv(c, conv(d, e))))
it gave me the correct result but its tagging an extra zero onto the end of my result. i assume this means its coming out as one higher power then it is supposed to be with a "0" constant. anyone see any problems here?
my answer is supposed to come out as
p = [1, 0.2, -2.2, -3.92, .4704]
while my work is giving me
p = [1, 0.2, -2.2, -3.92, .4704, 0]
so somewhere it is giving me an extra power of x and im not sure why use matlab to carry out the following multiplication of polynomials
(x+1.4)(x-0.4)x(x+0.6)(x-1.4)
heres what i did—
a = [1,1.4];
b = [1, -.4];
c = [1, 0];
d = [1, .6];
e = [1, -1.4];
p = conv(a, conv(b, conv(c, conv(d, e))))
it gave me the correct result but its tagging an extra zero onto the end of my result. i assume this means its coming out as one higher power then it is supposed to be with a "0" constant. anyone see any problems here?
my answer is supposed to come out as
p = [1, 0.2, -2.2, -3.92, .4704]
while my work is giving me
p = [1, 0.2, -2.2, -3.92, .4704, 0]
so somewhere it is giving me an extra power of x and im not sure why polynomials MATLAB Answers — New Questions
ECG Segmentation and Classification using PQRST
Hello MATLAB community,
I’m working on ECG classification using MATLAB, and my data is stored in CSV format with 13 columns (time + 12 leads). I’m interested in extracting PQRST segments using the segmentation method described in this MATLAB code: ECG Segmentation and Filtering.
I have a few questions regarding preprocessing:
Should I apply low-pass filters to all recordings to enhance signal quality?
I intend to retain various types of noise in the data to ensure model robustness. What are your recommendations on managing noise while preserving the integrity of PQRST segments?
Additionally, I’m curious about segmentation approach:
Should I perform segmentation separately for each of the 12 leads, or should I merge them before segmentation? What would be the pros and cons of each approach?
Here an example of an ECG data:
Any insights or suggestions on adapting the segmentation method and handling data preprocessing would be greatly appreciated. Thank you!Hello MATLAB community,
I’m working on ECG classification using MATLAB, and my data is stored in CSV format with 13 columns (time + 12 leads). I’m interested in extracting PQRST segments using the segmentation method described in this MATLAB code: ECG Segmentation and Filtering.
I have a few questions regarding preprocessing:
Should I apply low-pass filters to all recordings to enhance signal quality?
I intend to retain various types of noise in the data to ensure model robustness. What are your recommendations on managing noise while preserving the integrity of PQRST segments?
Additionally, I’m curious about segmentation approach:
Should I perform segmentation separately for each of the 12 leads, or should I merge them before segmentation? What would be the pros and cons of each approach?
Here an example of an ECG data:
Any insights or suggestions on adapting the segmentation method and handling data preprocessing would be greatly appreciated. Thank you! Hello MATLAB community,
I’m working on ECG classification using MATLAB, and my data is stored in CSV format with 13 columns (time + 12 leads). I’m interested in extracting PQRST segments using the segmentation method described in this MATLAB code: ECG Segmentation and Filtering.
I have a few questions regarding preprocessing:
Should I apply low-pass filters to all recordings to enhance signal quality?
I intend to retain various types of noise in the data to ensure model robustness. What are your recommendations on managing noise while preserving the integrity of PQRST segments?
Additionally, I’m curious about segmentation approach:
Should I perform segmentation separately for each of the 12 leads, or should I merge them before segmentation? What would be the pros and cons of each approach?
Here an example of an ECG data:
Any insights or suggestions on adapting the segmentation method and handling data preprocessing would be greatly appreciated. Thank you! ecg, ptb-xl, signal processing, pqrst, segmentation MATLAB Answers — New Questions
How to solve Simultaneous equations
3x+2y=0
x+y=43x+2y=0
x+y=4 3x+2y=0
x+y=4 sim MATLAB Answers — New Questions
What could be the reason why my model does not give accurate results as I planned?
Hi everyone. First of all, thank you for your time. This will be my first question on the matlab platform. Please excuse me if I have any mistakes. If you understand the problem, you can already find the necessary files in the zip folder. If you want to view images in pgm format, you can use the GIMP application.
I am planning to design a MLP image processing model without using any toolbox.
I plan to train my model by reading one by one 32×30 scale images in the CMU face images dataset I obtained from the internet and then continue with testing process.
(I use imread function that is provided by MATLAB)
INPUT is a cell vector which contains image matrixes in each element. So each element represents an image actually. While processing samples one by one I get its images as column vector.
Here is the code for file operations and image reading:
clc;clear;close;
%*****************Reading Images**************
myFolder = ”; %% Images folder path
if ~isfolder(myFolder) %% Checking if the folder doesn’t exist
errorMessage = sprintf(‘Error: The following folder does not exist:n%snPlease specify a new folder.’, myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
filePattern = fullfile(myFolder, ‘*.pgm’);
theFiles = dir(filePattern);
% Define the number of image files in the folder
numImages = length(theFiles);
% Initialize a cell array to store the images
INPUT = cell(numImages, 1);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
INPUT{k} = imread(fullFileName);
imshow(INPUT{k}); % Display image.
drawnow; % Force display to update immediately.
end
%***********************************************
It is a user-interactive model, and firstly I get the number of:
Hidden layers:
Neurons in each hidden layer: (neuron numbers will be the same for each hidden layer)
Max iteration:
of my model from user.
Other definitions are shown in below code. I define NumberOfInput as 960 which comes from 32×30 because Weight matrix’s size between input layer and first hidden layer needed to adjusted in that way.
Weight matrix values are assigned randomly.
My model should return 0 if person doesn’t wear sunglasses and 1 if person wears with high accuracy. So it is scaler and there will be 1 output obviously.
I studied about MLP models and I found that finding perfect variables is a hard subject in machine learning and it depends on application and tests. So I defined my ETA with various values: 0.01,0.02,0.05,0.2,0.5….
In this type of model input to neurons are defined as netH and output of these neurons are defined as H except last connections. In there they become netO and O.
Also sigma size is defined in order to use after forward state (backward state starts).
My model is an example of Supervised Learning and it needs some outputs for training images like mentioned DESIRED as below. Images inside Model_Training are located as open–>sunglasses–>open–>sunglasses… so I decided to define desired with this order as shown below.
Here is the code:
%*******************VARİABLES*******************
NumberOfPatterns=numImages;
NumberOfInput=960;
NumberOfOutput=1;
LearningRate_ETA=0.5;
while true
NofLayers=input("Layer number: "); % Hidden layer number
Nofneurons=input("Neuron number: "); % Neuron number of each hidden layer
Max_iteration=input("Max iteration number: "); % Max iteration
if(Nofneurons<=0 || NofLayers<=0 || Max_iteration<=0)
fprintf("These values can’t be accepted !");
fprintf("nPlease enter again");
else
break;
end
end
W = cell(NofLayers+1,1);
H=cell(NofLayers,1);
sigma=cell(NofLayers+1,1);
%***********************************************
% Random values are assigned to Weights
for i=1:NofLayers+1
if i==1
W{i}=rand(NumberOfInput,Nofneurons);
elseif i==NofLayers+1
W{i}=rand(Nofneurons,NumberOfOutput);
else
W{i}=rand(Nofneurons,Nofneurons);
end
end
%***********************************************
DESIRED=zeros(NumberOfPatterns,1);
%****************Adjusting Desired Results******
%Training images are located in order. Ex:
%A_open.pgn
%A_sunglasses.pgn
for i=1:NumberOfPatterns
if(mod(i,2)==1)
DESIRED(i)=0;
else
DESIRED(i)=1;
end
end
%************************************************
Right now processing starts. I need to mention that I use sigmoid function as activation function.
In order not to prolong the topic further I will share directly code in here.
%***********************Processing***************
for a=1:Max_iteration
totalerr=0;
for i = 1:NumberOfPatterns
ImageVector = reshape(INPUT{i}, [], 1);
X = double(ImageVector);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);%%%
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
O=sigmoid(netO);
else % between connections layers
netH=W{lay}’*H{lay-1}; %
H{lay}=sigmoid(netH);%
end
end
err=DESIRED(i)-O;
for j=1:NumberOfOutput
sigma{NofLayers+1}=err*O(j)*(1-O(j)); %Last sigma value
end
for l=1:NofLayers
for k=1:Nofneurons
[rowsigma colsigma]=size(sigma{NofLayers-l+2});
[rowW colsW]=size(W{NofLayers-l+2}(k,:));
%These conditions satisfies proper matrix multiplciation
if(colsigma==rowW)
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:) *H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
else
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:)’*H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
end
end
end
for z=1:NofLayers+1
%Weights are updated at this part
if((NofLayers+2-z)==1)
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*X*sigma{NofLayers+2-z};
else
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*H{NofLayers+1-z}*sigma{NofLayers+2-z};
end
end
totalerr=totalerr+0.5*err^2;
end
cost(a)=totalerr;
end
plot(cost);
%%*****************Test Case********************
%Getting test image address from user
fileFilter = ‘*.pgm’;
[filename, pathname] = uigetfile(fileFilter, ‘Select a PGM file’, ”);
if isequal(filename, 0)
disp(‘Program has stopped’);
else
fullFilePath = fullfile(pathname, filename);
end
%**************Test Sample Operations*******
testSample=imread(fullFilePath); %
testSample=reshape(testSample,[],1);
X=double(testSample);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
Out=round(sigmoid(netO));
else % between connections layers
netH=W{lay}’*H{lay-1};
H{lay}=sigmoid(netH);
end
end
fprintf(‘Result is: %dn’, Out);
%**********************Helper Functions*********
%Sigmoid Activation Function
function y = sigmoid(x)
y = 1 ./ (1 + exp(-x));
end
You can run and test it with the files that provided in zip file. In this kind of model as I know I need to try it with high number of layer and neuron. I tried with 4-20 5-30 5-35 … Generally it returns 1 and this is the problem that I am struggling with.
If you can give any comment, feedback I would appreciate it. Again thank you for giving a time.Hi everyone. First of all, thank you for your time. This will be my first question on the matlab platform. Please excuse me if I have any mistakes. If you understand the problem, you can already find the necessary files in the zip folder. If you want to view images in pgm format, you can use the GIMP application.
I am planning to design a MLP image processing model without using any toolbox.
I plan to train my model by reading one by one 32×30 scale images in the CMU face images dataset I obtained from the internet and then continue with testing process.
(I use imread function that is provided by MATLAB)
INPUT is a cell vector which contains image matrixes in each element. So each element represents an image actually. While processing samples one by one I get its images as column vector.
Here is the code for file operations and image reading:
clc;clear;close;
%*****************Reading Images**************
myFolder = ”; %% Images folder path
if ~isfolder(myFolder) %% Checking if the folder doesn’t exist
errorMessage = sprintf(‘Error: The following folder does not exist:n%snPlease specify a new folder.’, myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
filePattern = fullfile(myFolder, ‘*.pgm’);
theFiles = dir(filePattern);
% Define the number of image files in the folder
numImages = length(theFiles);
% Initialize a cell array to store the images
INPUT = cell(numImages, 1);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
INPUT{k} = imread(fullFileName);
imshow(INPUT{k}); % Display image.
drawnow; % Force display to update immediately.
end
%***********************************************
It is a user-interactive model, and firstly I get the number of:
Hidden layers:
Neurons in each hidden layer: (neuron numbers will be the same for each hidden layer)
Max iteration:
of my model from user.
Other definitions are shown in below code. I define NumberOfInput as 960 which comes from 32×30 because Weight matrix’s size between input layer and first hidden layer needed to adjusted in that way.
Weight matrix values are assigned randomly.
My model should return 0 if person doesn’t wear sunglasses and 1 if person wears with high accuracy. So it is scaler and there will be 1 output obviously.
I studied about MLP models and I found that finding perfect variables is a hard subject in machine learning and it depends on application and tests. So I defined my ETA with various values: 0.01,0.02,0.05,0.2,0.5….
In this type of model input to neurons are defined as netH and output of these neurons are defined as H except last connections. In there they become netO and O.
Also sigma size is defined in order to use after forward state (backward state starts).
My model is an example of Supervised Learning and it needs some outputs for training images like mentioned DESIRED as below. Images inside Model_Training are located as open–>sunglasses–>open–>sunglasses… so I decided to define desired with this order as shown below.
Here is the code:
%*******************VARİABLES*******************
NumberOfPatterns=numImages;
NumberOfInput=960;
NumberOfOutput=1;
LearningRate_ETA=0.5;
while true
NofLayers=input("Layer number: "); % Hidden layer number
Nofneurons=input("Neuron number: "); % Neuron number of each hidden layer
Max_iteration=input("Max iteration number: "); % Max iteration
if(Nofneurons<=0 || NofLayers<=0 || Max_iteration<=0)
fprintf("These values can’t be accepted !");
fprintf("nPlease enter again");
else
break;
end
end
W = cell(NofLayers+1,1);
H=cell(NofLayers,1);
sigma=cell(NofLayers+1,1);
%***********************************************
% Random values are assigned to Weights
for i=1:NofLayers+1
if i==1
W{i}=rand(NumberOfInput,Nofneurons);
elseif i==NofLayers+1
W{i}=rand(Nofneurons,NumberOfOutput);
else
W{i}=rand(Nofneurons,Nofneurons);
end
end
%***********************************************
DESIRED=zeros(NumberOfPatterns,1);
%****************Adjusting Desired Results******
%Training images are located in order. Ex:
%A_open.pgn
%A_sunglasses.pgn
for i=1:NumberOfPatterns
if(mod(i,2)==1)
DESIRED(i)=0;
else
DESIRED(i)=1;
end
end
%************************************************
Right now processing starts. I need to mention that I use sigmoid function as activation function.
In order not to prolong the topic further I will share directly code in here.
%***********************Processing***************
for a=1:Max_iteration
totalerr=0;
for i = 1:NumberOfPatterns
ImageVector = reshape(INPUT{i}, [], 1);
X = double(ImageVector);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);%%%
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
O=sigmoid(netO);
else % between connections layers
netH=W{lay}’*H{lay-1}; %
H{lay}=sigmoid(netH);%
end
end
err=DESIRED(i)-O;
for j=1:NumberOfOutput
sigma{NofLayers+1}=err*O(j)*(1-O(j)); %Last sigma value
end
for l=1:NofLayers
for k=1:Nofneurons
[rowsigma colsigma]=size(sigma{NofLayers-l+2});
[rowW colsW]=size(W{NofLayers-l+2}(k,:));
%These conditions satisfies proper matrix multiplciation
if(colsigma==rowW)
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:) *H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
else
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:)’*H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
end
end
end
for z=1:NofLayers+1
%Weights are updated at this part
if((NofLayers+2-z)==1)
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*X*sigma{NofLayers+2-z};
else
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*H{NofLayers+1-z}*sigma{NofLayers+2-z};
end
end
totalerr=totalerr+0.5*err^2;
end
cost(a)=totalerr;
end
plot(cost);
%%*****************Test Case********************
%Getting test image address from user
fileFilter = ‘*.pgm’;
[filename, pathname] = uigetfile(fileFilter, ‘Select a PGM file’, ”);
if isequal(filename, 0)
disp(‘Program has stopped’);
else
fullFilePath = fullfile(pathname, filename);
end
%**************Test Sample Operations*******
testSample=imread(fullFilePath); %
testSample=reshape(testSample,[],1);
X=double(testSample);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
Out=round(sigmoid(netO));
else % between connections layers
netH=W{lay}’*H{lay-1};
H{lay}=sigmoid(netH);
end
end
fprintf(‘Result is: %dn’, Out);
%**********************Helper Functions*********
%Sigmoid Activation Function
function y = sigmoid(x)
y = 1 ./ (1 + exp(-x));
end
You can run and test it with the files that provided in zip file. In this kind of model as I know I need to try it with high number of layer and neuron. I tried with 4-20 5-30 5-35 … Generally it returns 1 and this is the problem that I am struggling with.
If you can give any comment, feedback I would appreciate it. Again thank you for giving a time. Hi everyone. First of all, thank you for your time. This will be my first question on the matlab platform. Please excuse me if I have any mistakes. If you understand the problem, you can already find the necessary files in the zip folder. If you want to view images in pgm format, you can use the GIMP application.
I am planning to design a MLP image processing model without using any toolbox.
I plan to train my model by reading one by one 32×30 scale images in the CMU face images dataset I obtained from the internet and then continue with testing process.
(I use imread function that is provided by MATLAB)
INPUT is a cell vector which contains image matrixes in each element. So each element represents an image actually. While processing samples one by one I get its images as column vector.
Here is the code for file operations and image reading:
clc;clear;close;
%*****************Reading Images**************
myFolder = ”; %% Images folder path
if ~isfolder(myFolder) %% Checking if the folder doesn’t exist
errorMessage = sprintf(‘Error: The following folder does not exist:n%snPlease specify a new folder.’, myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
filePattern = fullfile(myFolder, ‘*.pgm’);
theFiles = dir(filePattern);
% Define the number of image files in the folder
numImages = length(theFiles);
% Initialize a cell array to store the images
INPUT = cell(numImages, 1);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
INPUT{k} = imread(fullFileName);
imshow(INPUT{k}); % Display image.
drawnow; % Force display to update immediately.
end
%***********************************************
It is a user-interactive model, and firstly I get the number of:
Hidden layers:
Neurons in each hidden layer: (neuron numbers will be the same for each hidden layer)
Max iteration:
of my model from user.
Other definitions are shown in below code. I define NumberOfInput as 960 which comes from 32×30 because Weight matrix’s size between input layer and first hidden layer needed to adjusted in that way.
Weight matrix values are assigned randomly.
My model should return 0 if person doesn’t wear sunglasses and 1 if person wears with high accuracy. So it is scaler and there will be 1 output obviously.
I studied about MLP models and I found that finding perfect variables is a hard subject in machine learning and it depends on application and tests. So I defined my ETA with various values: 0.01,0.02,0.05,0.2,0.5….
In this type of model input to neurons are defined as netH and output of these neurons are defined as H except last connections. In there they become netO and O.
Also sigma size is defined in order to use after forward state (backward state starts).
My model is an example of Supervised Learning and it needs some outputs for training images like mentioned DESIRED as below. Images inside Model_Training are located as open–>sunglasses–>open–>sunglasses… so I decided to define desired with this order as shown below.
Here is the code:
%*******************VARİABLES*******************
NumberOfPatterns=numImages;
NumberOfInput=960;
NumberOfOutput=1;
LearningRate_ETA=0.5;
while true
NofLayers=input("Layer number: "); % Hidden layer number
Nofneurons=input("Neuron number: "); % Neuron number of each hidden layer
Max_iteration=input("Max iteration number: "); % Max iteration
if(Nofneurons<=0 || NofLayers<=0 || Max_iteration<=0)
fprintf("These values can’t be accepted !");
fprintf("nPlease enter again");
else
break;
end
end
W = cell(NofLayers+1,1);
H=cell(NofLayers,1);
sigma=cell(NofLayers+1,1);
%***********************************************
% Random values are assigned to Weights
for i=1:NofLayers+1
if i==1
W{i}=rand(NumberOfInput,Nofneurons);
elseif i==NofLayers+1
W{i}=rand(Nofneurons,NumberOfOutput);
else
W{i}=rand(Nofneurons,Nofneurons);
end
end
%***********************************************
DESIRED=zeros(NumberOfPatterns,1);
%****************Adjusting Desired Results******
%Training images are located in order. Ex:
%A_open.pgn
%A_sunglasses.pgn
for i=1:NumberOfPatterns
if(mod(i,2)==1)
DESIRED(i)=0;
else
DESIRED(i)=1;
end
end
%************************************************
Right now processing starts. I need to mention that I use sigmoid function as activation function.
In order not to prolong the topic further I will share directly code in here.
%***********************Processing***************
for a=1:Max_iteration
totalerr=0;
for i = 1:NumberOfPatterns
ImageVector = reshape(INPUT{i}, [], 1);
X = double(ImageVector);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);%%%
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
O=sigmoid(netO);
else % between connections layers
netH=W{lay}’*H{lay-1}; %
H{lay}=sigmoid(netH);%
end
end
err=DESIRED(i)-O;
for j=1:NumberOfOutput
sigma{NofLayers+1}=err*O(j)*(1-O(j)); %Last sigma value
end
for l=1:NofLayers
for k=1:Nofneurons
[rowsigma colsigma]=size(sigma{NofLayers-l+2});
[rowW colsW]=size(W{NofLayers-l+2}(k,:));
%These conditions satisfies proper matrix multiplciation
if(colsigma==rowW)
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:) *H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
else
sigma{NofLayers-l+1}=sigma{NofLayers-l+2}*W{NofLayers-l+2}(k,:)’*H{NofLayers+1-l}(k)*(1-H{NofLayers+1-l}(k));
end
end
end
for z=1:NofLayers+1
%Weights are updated at this part
if((NofLayers+2-z)==1)
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*X*sigma{NofLayers+2-z};
else
W{NofLayers+2-z}=W{NofLayers+2-z}+LearningRate_ETA*H{NofLayers+1-z}*sigma{NofLayers+2-z};
end
end
totalerr=totalerr+0.5*err^2;
end
cost(a)=totalerr;
end
plot(cost);
%%*****************Test Case********************
%Getting test image address from user
fileFilter = ‘*.pgm’;
[filename, pathname] = uigetfile(fileFilter, ‘Select a PGM file’, ”);
if isequal(filename, 0)
disp(‘Program has stopped’);
else
fullFilePath = fullfile(pathname, filename);
end
%**************Test Sample Operations*******
testSample=imread(fullFilePath); %
testSample=reshape(testSample,[],1);
X=double(testSample);
for lay=1:NofLayers+1
if(lay==1) %First connections
netH=W{lay}’*X;
H{lay}=sigmoid(netH);
elseif (lay==NofLayers+1) %Last connections
netO=W{lay}’*H{lay-1};
Out=round(sigmoid(netO));
else % between connections layers
netH=W{lay}’*H{lay-1};
H{lay}=sigmoid(netH);
end
end
fprintf(‘Result is: %dn’, Out);
%**********************Helper Functions*********
%Sigmoid Activation Function
function y = sigmoid(x)
y = 1 ./ (1 + exp(-x));
end
You can run and test it with the files that provided in zip file. In this kind of model as I know I need to try it with high number of layer and neuron. I tried with 4-20 5-30 5-35 … Generally it returns 1 and this is the problem that I am struggling with.
If you can give any comment, feedback I would appreciate it. Again thank you for giving a time. mlp, image processing, deep learning MATLAB Answers — New Questions
how to open image .mhd
DEAR ALL,
Anyone know how to open this image as attached.DEAR ALL,
Anyone know how to open this image as attached. DEAR ALL,
Anyone know how to open this image as attached. image processing, image acquisition, digital image processing, image analysis, image segmentation MATLAB Answers — New Questions
use simulink function caller error
hello, when i try use function caller to call the subfunction, following eror happens, how to resolve it.hello, when i try use function caller to call the subfunction, following eror happens, how to resolve it. hello, when i try use function caller to call the subfunction, following eror happens, how to resolve it. function caller, simulink MATLAB Answers — New Questions
how can i plot graph of skin friction using the bellow code.
what changes are required in this code
function slipflow
format long g
%Define all parameters
% Boundary layer thickness & stepsize
etaMin = 0;
etaMax1 = 15;
etaMax2 = 15; %15, 10
stepsize1 = etaMax1;
stepsize2 = etaMax2;
% Input for the parameters
A=1; %velocity slip
B=0.2; %thermal slip
beta=0.02; %heat gen/abs
S=2.4; %suction(2.3,2.4,2.5)
Pr=6.2; %prandtl number
lambda=-1; %stretching shrinking
a=0.01; %phil-1st nanoparticle concentration
b=0.01; %(0.01,0.05)phi2-2nd nanoparticle concentration
c=a+b; %phi-hnf concentration of hybrid nanoparticle
%%%%%%%%%%% 1st nanoparticle properties (Al2O3)%%%%%%%%%%%%
C1=765;
P1=3970;
K1=40;
B1=0.85/((10)^5);
s1=35*(10)^6; %MHD
%%%%%%%%%%% 2nd nanoparticle properties (Cu)%%%%%%%%%%%%
C2=385; %specific heat
P2=8933; %density
K2=400; %thermal conductivity
B2=1.67/((10)^5); %thermal expansion
s2=(59.6)*(10)^6; %MHD
%%%%%%%%%%% Base fluid properties %%%%%%%%%%%%
C3=4179; %specific heat
P3=997.1; %density
K3=0.613; %thermal conductivity
B3=21/((10)^5); %thermal expansion
s3=0.05; %MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%multiplier%%%%%%%%%%%%%%%%%%%
H1=P1*C1; %pho*cp nanoparticle 1
H2=P2*C2; %pho*cp nanoparticle 2
H3=P3*C3; %pho*cp base fluid
H4=a*H1+b*H2+(1-c)*H3; %pho*cp hybrid nanofluid
H5=a*P1+b*P2+(1-c)*P3; %pho hybrid nanofluid
H6=1/((1-c)^2.5); % mu hybrid nanofluid / mu base fluid
H7=a*(P1*B1)+b*(P2*B2)+(1-c)*(P3*B3); % thermal expansion of hybrid nanofluid
%Kn=K3*(K1+2*K3-2*a*(K3-K1))/(K1+2*K3+a*(K3-K1)); %thermal conductivity of nanofluid
Kh=(((a*K1+b*K2)/c)+2*K3+2*(a*K1+b*K2)-2*c*K3)/(((a*K1+b*K2)/c)+2*K3-(a*K1+b*K2)-2*c*K3); %khnf/kf
H8=(((a*s1+b*s2)/c)+2*s3+2*(a*s1+b*s2)-2*c*s3)/(((a*s1+b*s2)/c)+2*s3-(a*s1+b*s2)-2*c*s3); % sigma hnf/ sigma f
D1=(H5/P3)/H6;
D3=(H7/(P3*B3))/(H5/P3); % multiplier of boundary parameter
D2= Pr*((H4/H3)/Kh);
D4=H8/(H5/P3); %multiplier MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax1, stepsize1),@(x)OdeInit1(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta = linspace (etaMin, etaMax1, stepsize1);
y= deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’-‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’-‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for first solution
descris =[sol.x; sol.y];
save ‘sliphybrid_upper.txt’ descris -ascii
% Displaying the output for first solution
fprintf(‘n First solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% second solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax2, stepsize2),@(x)OdeInit2(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta= linspace (etaMin, etaMax2, stepsize2);
y = deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’–‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’–‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for second solution
descris=[sol.x; sol.y];
save ‘sliphybrid_lower.txt’descris -ascii
% Displaying the output for first solution
fprintf(‘nSecond solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
% Define the ODE function
function f = OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta)
f =[y(2);y(3);D1*(2*(y(2)*y(2))-y(1)*y(3));y(5);(Pr/Kh)*((-H4/H3)*(y(1)*y(5)-y(2)*y(4))-beta*y(4))];
end
% Define the boundary conditions
function res = OdeBC(ya, yb, A, S, B, lambda)
res= [ya(1)-S;ya(2)-lambda-A*ya(3);ya(4)-1-B*ya(5);yb(2);yb(4)];
end
% setting the initial guess for first solution
function v = OdeInit1(x,A,S,lambda)
v=[S+0.56;0;0;0;0];
end
% setting the initial guess for second solution
function v1 =OdeInit2(x, A, S,lambda)
v1 = [exp(-x);exp(-x);-exp(-x);-exp(-x);-exp(-x)];
endwhat changes are required in this code
function slipflow
format long g
%Define all parameters
% Boundary layer thickness & stepsize
etaMin = 0;
etaMax1 = 15;
etaMax2 = 15; %15, 10
stepsize1 = etaMax1;
stepsize2 = etaMax2;
% Input for the parameters
A=1; %velocity slip
B=0.2; %thermal slip
beta=0.02; %heat gen/abs
S=2.4; %suction(2.3,2.4,2.5)
Pr=6.2; %prandtl number
lambda=-1; %stretching shrinking
a=0.01; %phil-1st nanoparticle concentration
b=0.01; %(0.01,0.05)phi2-2nd nanoparticle concentration
c=a+b; %phi-hnf concentration of hybrid nanoparticle
%%%%%%%%%%% 1st nanoparticle properties (Al2O3)%%%%%%%%%%%%
C1=765;
P1=3970;
K1=40;
B1=0.85/((10)^5);
s1=35*(10)^6; %MHD
%%%%%%%%%%% 2nd nanoparticle properties (Cu)%%%%%%%%%%%%
C2=385; %specific heat
P2=8933; %density
K2=400; %thermal conductivity
B2=1.67/((10)^5); %thermal expansion
s2=(59.6)*(10)^6; %MHD
%%%%%%%%%%% Base fluid properties %%%%%%%%%%%%
C3=4179; %specific heat
P3=997.1; %density
K3=0.613; %thermal conductivity
B3=21/((10)^5); %thermal expansion
s3=0.05; %MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%multiplier%%%%%%%%%%%%%%%%%%%
H1=P1*C1; %pho*cp nanoparticle 1
H2=P2*C2; %pho*cp nanoparticle 2
H3=P3*C3; %pho*cp base fluid
H4=a*H1+b*H2+(1-c)*H3; %pho*cp hybrid nanofluid
H5=a*P1+b*P2+(1-c)*P3; %pho hybrid nanofluid
H6=1/((1-c)^2.5); % mu hybrid nanofluid / mu base fluid
H7=a*(P1*B1)+b*(P2*B2)+(1-c)*(P3*B3); % thermal expansion of hybrid nanofluid
%Kn=K3*(K1+2*K3-2*a*(K3-K1))/(K1+2*K3+a*(K3-K1)); %thermal conductivity of nanofluid
Kh=(((a*K1+b*K2)/c)+2*K3+2*(a*K1+b*K2)-2*c*K3)/(((a*K1+b*K2)/c)+2*K3-(a*K1+b*K2)-2*c*K3); %khnf/kf
H8=(((a*s1+b*s2)/c)+2*s3+2*(a*s1+b*s2)-2*c*s3)/(((a*s1+b*s2)/c)+2*s3-(a*s1+b*s2)-2*c*s3); % sigma hnf/ sigma f
D1=(H5/P3)/H6;
D3=(H7/(P3*B3))/(H5/P3); % multiplier of boundary parameter
D2= Pr*((H4/H3)/Kh);
D4=H8/(H5/P3); %multiplier MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax1, stepsize1),@(x)OdeInit1(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta = linspace (etaMin, etaMax1, stepsize1);
y= deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’-‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’-‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for first solution
descris =[sol.x; sol.y];
save ‘sliphybrid_upper.txt’ descris -ascii
% Displaying the output for first solution
fprintf(‘n First solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% second solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax2, stepsize2),@(x)OdeInit2(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta= linspace (etaMin, etaMax2, stepsize2);
y = deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’–‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’–‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for second solution
descris=[sol.x; sol.y];
save ‘sliphybrid_lower.txt’descris -ascii
% Displaying the output for first solution
fprintf(‘nSecond solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
% Define the ODE function
function f = OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta)
f =[y(2);y(3);D1*(2*(y(2)*y(2))-y(1)*y(3));y(5);(Pr/Kh)*((-H4/H3)*(y(1)*y(5)-y(2)*y(4))-beta*y(4))];
end
% Define the boundary conditions
function res = OdeBC(ya, yb, A, S, B, lambda)
res= [ya(1)-S;ya(2)-lambda-A*ya(3);ya(4)-1-B*ya(5);yb(2);yb(4)];
end
% setting the initial guess for first solution
function v = OdeInit1(x,A,S,lambda)
v=[S+0.56;0;0;0;0];
end
% setting the initial guess for second solution
function v1 =OdeInit2(x, A, S,lambda)
v1 = [exp(-x);exp(-x);-exp(-x);-exp(-x);-exp(-x)];
end what changes are required in this code
function slipflow
format long g
%Define all parameters
% Boundary layer thickness & stepsize
etaMin = 0;
etaMax1 = 15;
etaMax2 = 15; %15, 10
stepsize1 = etaMax1;
stepsize2 = etaMax2;
% Input for the parameters
A=1; %velocity slip
B=0.2; %thermal slip
beta=0.02; %heat gen/abs
S=2.4; %suction(2.3,2.4,2.5)
Pr=6.2; %prandtl number
lambda=-1; %stretching shrinking
a=0.01; %phil-1st nanoparticle concentration
b=0.01; %(0.01,0.05)phi2-2nd nanoparticle concentration
c=a+b; %phi-hnf concentration of hybrid nanoparticle
%%%%%%%%%%% 1st nanoparticle properties (Al2O3)%%%%%%%%%%%%
C1=765;
P1=3970;
K1=40;
B1=0.85/((10)^5);
s1=35*(10)^6; %MHD
%%%%%%%%%%% 2nd nanoparticle properties (Cu)%%%%%%%%%%%%
C2=385; %specific heat
P2=8933; %density
K2=400; %thermal conductivity
B2=1.67/((10)^5); %thermal expansion
s2=(59.6)*(10)^6; %MHD
%%%%%%%%%%% Base fluid properties %%%%%%%%%%%%
C3=4179; %specific heat
P3=997.1; %density
K3=0.613; %thermal conductivity
B3=21/((10)^5); %thermal expansion
s3=0.05; %MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%multiplier%%%%%%%%%%%%%%%%%%%
H1=P1*C1; %pho*cp nanoparticle 1
H2=P2*C2; %pho*cp nanoparticle 2
H3=P3*C3; %pho*cp base fluid
H4=a*H1+b*H2+(1-c)*H3; %pho*cp hybrid nanofluid
H5=a*P1+b*P2+(1-c)*P3; %pho hybrid nanofluid
H6=1/((1-c)^2.5); % mu hybrid nanofluid / mu base fluid
H7=a*(P1*B1)+b*(P2*B2)+(1-c)*(P3*B3); % thermal expansion of hybrid nanofluid
%Kn=K3*(K1+2*K3-2*a*(K3-K1))/(K1+2*K3+a*(K3-K1)); %thermal conductivity of nanofluid
Kh=(((a*K1+b*K2)/c)+2*K3+2*(a*K1+b*K2)-2*c*K3)/(((a*K1+b*K2)/c)+2*K3-(a*K1+b*K2)-2*c*K3); %khnf/kf
H8=(((a*s1+b*s2)/c)+2*s3+2*(a*s1+b*s2)-2*c*s3)/(((a*s1+b*s2)/c)+2*s3-(a*s1+b*s2)-2*c*s3); % sigma hnf/ sigma f
D1=(H5/P3)/H6;
D3=(H7/(P3*B3))/(H5/P3); % multiplier of boundary parameter
D2= Pr*((H4/H3)/Kh);
D4=H8/(H5/P3); %multiplier MHD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax1, stepsize1),@(x)OdeInit1(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta = linspace (etaMin, etaMax1, stepsize1);
y= deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’-‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’-‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for first solution
descris =[sol.x; sol.y];
save ‘sliphybrid_upper.txt’ descris -ascii
% Displaying the output for first solution
fprintf(‘n First solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% second solution %%%%%%%%%%%%%%%%%%%
options = bvpset(‘stats’,’off’,’RelTol’,1e-10);
solinit = bvpinit (linspace (etaMin, etaMax2, stepsize2),@(x)OdeInit2(x,A,S,lambda));
sol = bvp4c (@(x,y)OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta), @(ya,yb)OdeBC(ya, yb, A, S, B, lambda), solinit, options);
eta= linspace (etaMin, etaMax2, stepsize2);
y = deval (sol,eta);
figure(1) %velocity profile
plot(sol.x,sol.y(2,:),’–‘)
xlabel(‘eta’)
ylabel(‘f`(eta)’)
hold on
figure(2) %temperature profile
plot(sol.x,sol.y(4,:),’–‘)
xlabel(‘eta’)
ylabel(‘theta(eta)’)
hold on
% saving the out put in text file for second solution
descris=[sol.x; sol.y];
save ‘sliphybrid_lower.txt’descris -ascii
% Displaying the output for first solution
fprintf(‘nSecond solution:n’);
fprintf(‘f"(0)=%7.9fn’,y(3)); % reduced skin friction
fprintf(‘-theta(0)=%7.9fn’,-y(5)); %reduced local nusselt number
fprintf(‘Cfx=%7.9fn’,H6*(y(3))); % skin friction
fprintf(‘Nux=%7.9fn’,-Kh*y(5)); % local nusselt number
fprintf(‘n’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
% Define the ODE function
function f = OdeBVP(x,y,Pr,D1,Kh,H4,H3,beta)
f =[y(2);y(3);D1*(2*(y(2)*y(2))-y(1)*y(3));y(5);(Pr/Kh)*((-H4/H3)*(y(1)*y(5)-y(2)*y(4))-beta*y(4))];
end
% Define the boundary conditions
function res = OdeBC(ya, yb, A, S, B, lambda)
res= [ya(1)-S;ya(2)-lambda-A*ya(3);ya(4)-1-B*ya(5);yb(2);yb(4)];
end
% setting the initial guess for first solution
function v = OdeInit1(x,A,S,lambda)
v=[S+0.56;0;0;0;0];
end
% setting the initial guess for second solution
function v1 =OdeInit2(x, A, S,lambda)
v1 = [exp(-x);exp(-x);-exp(-x);-exp(-x);-exp(-x)];
end matlab MATLAB Answers — New Questions
Call graph generation from VHDL code files.
I have many vhdl code files. Is there any way i can generate a call graph from MATLAB itself?I have many vhdl code files. Is there any way i can generate a call graph from MATLAB itself? I have many vhdl code files. Is there any way i can generate a call graph from MATLAB itself? hdlcoder, vhdl, dsp MATLAB Answers — New Questions
5g in smart grid ..
help me do my simulation for 5g in smart gridhelp me do my simulation for 5g in smart grid help me do my simulation for 5g in smart grid 5g in smart grid MATLAB Answers — New Questions
Export Model as FMU with Linux Binary on Windows
Hello Mathwork team:
I would like to export FMU according this documnent(Export Model as FMU with Linux Binary on Windows – MATLAB & Simulink – MathWorks China) .
but after I try generate FMU model, a error happened. it tell me “Failed to setup the environment. WSL must be at least version ‘2.0.9.0’. ”. Then I have check my WSL verison. it shows my WSL version is 2.2.4.0. and I have run WSL –update and try to update the version of WSL, but it tell me my WSL version is the latest one.
so I think my WSL is the latest one, but why simulink still reminde me that my WSL version is not ok? can you help me to solve it.
matlab verstion: 2024a update 4
FMU builder version: 24.1.1
thank youHello Mathwork team:
I would like to export FMU according this documnent(Export Model as FMU with Linux Binary on Windows – MATLAB & Simulink – MathWorks China) .
but after I try generate FMU model, a error happened. it tell me “Failed to setup the environment. WSL must be at least version ‘2.0.9.0’. ”. Then I have check my WSL verison. it shows my WSL version is 2.2.4.0. and I have run WSL –update and try to update the version of WSL, but it tell me my WSL version is the latest one.
so I think my WSL is the latest one, but why simulink still reminde me that my WSL version is not ok? can you help me to solve it.
matlab verstion: 2024a update 4
FMU builder version: 24.1.1
thank you Hello Mathwork team:
I would like to export FMU according this documnent(Export Model as FMU with Linux Binary on Windows – MATLAB & Simulink – MathWorks China) .
but after I try generate FMU model, a error happened. it tell me “Failed to setup the environment. WSL must be at least version ‘2.0.9.0’. ”. Then I have check my WSL verison. it shows my WSL version is 2.2.4.0. and I have run WSL –update and try to update the version of WSL, but it tell me my WSL version is the latest one.
so I think my WSL is the latest one, but why simulink still reminde me that my WSL version is not ok? can you help me to solve it.
matlab verstion: 2024a update 4
FMU builder version: 24.1.1
thank you fmu linux MATLAB Answers — New Questions
how can i plot graph of skin friction and nusselt number and how can i get different points to plot them
I want to plt graph of skin friction,nusselt number and sheerwod number. what changes are required in the code.I want to plt graph of skin friction,nusselt number and sheerwod number. what changes are required in the code. I want to plt graph of skin friction,nusselt number and sheerwod number. what changes are required in the code. matlab MATLAB Answers — New Questions
Farfield pattern reconstruction using 2D interpolation in matlab
I am trying to use fourier transform based approach for near field to farfield transformation of E-fields. I have my sampling plane in xy with following coordinates -120mm <X<120mm and -120mm<Y<120mm. My operating frequency is 2.5 GHz to 4GHz. I have taken fourier transform for the E-field complex data and have converted my FFT indices into wavenumbers. In order to do the Near field to farfield transformation, I have to then interpolate the FFT values to the stationary observation points in spherical coordinates. So, i used interp2 function to do this. The following is my code for this interpolation.
Ex_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Exff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
Ey_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Eyff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
i= number of frequecies in my code. The Fx grid1 and Fy grid are the wavenumbers in cartesian coordinates already in gridded format. Their size is 1024 x 1024. (FFT size=1024). The kx and ky are the observation points in cartesian coordinates calculated from the spherical coordinates. The code works for me and it gives a farfield which closely matches the data from a Electromagnetic solver. But, the catch is that it matches only at lower frequencies, and as the frequency increases, the spline fit is giving me lot of inflections in my antenna beam pattern. I beleive this is related to the interpolation error. Because, when i change the interpolation type to ‘cubic’ it gives lot of ripples in my beam pattern. So, basically with the different types of interplation the final beam varies drastically at higher frequencies. I did not find any method better than spline in interp2 function. I do not know how to solve this issue. Are there any other methods available for 2D interpolation where we can also control the spline fitting parameters? Looking for some suggestions here.. I am new to these interpolation techniques, so i am not able to understand the problem completely here.I am trying to use fourier transform based approach for near field to farfield transformation of E-fields. I have my sampling plane in xy with following coordinates -120mm <X<120mm and -120mm<Y<120mm. My operating frequency is 2.5 GHz to 4GHz. I have taken fourier transform for the E-field complex data and have converted my FFT indices into wavenumbers. In order to do the Near field to farfield transformation, I have to then interpolate the FFT values to the stationary observation points in spherical coordinates. So, i used interp2 function to do this. The following is my code for this interpolation.
Ex_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Exff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
Ey_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Eyff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
i= number of frequecies in my code. The Fx grid1 and Fy grid are the wavenumbers in cartesian coordinates already in gridded format. Their size is 1024 x 1024. (FFT size=1024). The kx and ky are the observation points in cartesian coordinates calculated from the spherical coordinates. The code works for me and it gives a farfield which closely matches the data from a Electromagnetic solver. But, the catch is that it matches only at lower frequencies, and as the frequency increases, the spline fit is giving me lot of inflections in my antenna beam pattern. I beleive this is related to the interpolation error. Because, when i change the interpolation type to ‘cubic’ it gives lot of ripples in my beam pattern. So, basically with the different types of interplation the final beam varies drastically at higher frequencies. I did not find any method better than spline in interp2 function. I do not know how to solve this issue. Are there any other methods available for 2D interpolation where we can also control the spline fitting parameters? Looking for some suggestions here.. I am new to these interpolation techniques, so i am not able to understand the problem completely here. I am trying to use fourier transform based approach for near field to farfield transformation of E-fields. I have my sampling plane in xy with following coordinates -120mm <X<120mm and -120mm<Y<120mm. My operating frequency is 2.5 GHz to 4GHz. I have taken fourier transform for the E-field complex data and have converted my FFT indices into wavenumbers. In order to do the Near field to farfield transformation, I have to then interpolate the FFT values to the stationary observation points in spherical coordinates. So, i used interp2 function to do this. The following is my code for this interpolation.
Ex_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Exff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
Ey_interp(:,:,i)= interp2(Fx_grid1, Fy_grid1, Eyff_z0(:,:,i), kx(:,:,i), ky(:,:,i), ‘spline’,0);
i= number of frequecies in my code. The Fx grid1 and Fy grid are the wavenumbers in cartesian coordinates already in gridded format. Their size is 1024 x 1024. (FFT size=1024). The kx and ky are the observation points in cartesian coordinates calculated from the spherical coordinates. The code works for me and it gives a farfield which closely matches the data from a Electromagnetic solver. But, the catch is that it matches only at lower frequencies, and as the frequency increases, the spline fit is giving me lot of inflections in my antenna beam pattern. I beleive this is related to the interpolation error. Because, when i change the interpolation type to ‘cubic’ it gives lot of ripples in my beam pattern. So, basically with the different types of interplation the final beam varies drastically at higher frequencies. I did not find any method better than spline in interp2 function. I do not know how to solve this issue. Are there any other methods available for 2D interpolation where we can also control the spline fitting parameters? Looking for some suggestions here.. I am new to these interpolation techniques, so i am not able to understand the problem completely here. fft, image processing, antenna, interpolation, curve fitting, function, mathematics MATLAB Answers — New Questions
Some problems using map/container with if-else statement in nested for loops
Hi everyone, this is my following code with the use of map and container with if-else statement in nested for loops. I don’t understand why the error Unrecognized function or variable ‘Intensitysol1’ appears, while there is no problem for Intensitysol2. How should I fix it?
theta=0.65;
J=0.08;
for ii = 0:1:49;
omega_y(ii+1) = 0 + (0.15/100)*(ii);
end
for jj = 0:1:100;
omega_z(jj+1) = 0 -(0.15/100)*(jj);
end
valueset_omega_y_vector = 1:1:(length(omega_y));
valueset_omega_z_vector= 1:1:(length(omega_z));
M_omega_y = containers.Map(omega_y,valueset_omega_y_vector);
M_omega_z = containers.Map(omega_z, valueset_omega_z_vector);
for ii = 1:1:49
for jj = 0:1:100
u = 0 : 2*pi/1000 : 2*pi;
E_minus = 2*J*cos(theta).*cos(u) – (sqrt(omega_y(ii+1)^2 + omega_z(jj+1)^2 + 4*(J^2)*((sin(theta))^2).*((sin(u)).^2) -4*J*omega_z(jj+1)*sin(theta).*sin(u)));
TF = islocalmin(E_minus);
a=u(TF);
if size(a)==2
Intensitysol1(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(2);
elseif size(a)==1
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
end
end
end
figure(1)
surf(omega_z, omega_y, Intensitysol1)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’)
figure(2)
surf(omega_z, omega_y, Intensitysol2)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’)Hi everyone, this is my following code with the use of map and container with if-else statement in nested for loops. I don’t understand why the error Unrecognized function or variable ‘Intensitysol1’ appears, while there is no problem for Intensitysol2. How should I fix it?
theta=0.65;
J=0.08;
for ii = 0:1:49;
omega_y(ii+1) = 0 + (0.15/100)*(ii);
end
for jj = 0:1:100;
omega_z(jj+1) = 0 -(0.15/100)*(jj);
end
valueset_omega_y_vector = 1:1:(length(omega_y));
valueset_omega_z_vector= 1:1:(length(omega_z));
M_omega_y = containers.Map(omega_y,valueset_omega_y_vector);
M_omega_z = containers.Map(omega_z, valueset_omega_z_vector);
for ii = 1:1:49
for jj = 0:1:100
u = 0 : 2*pi/1000 : 2*pi;
E_minus = 2*J*cos(theta).*cos(u) – (sqrt(omega_y(ii+1)^2 + omega_z(jj+1)^2 + 4*(J^2)*((sin(theta))^2).*((sin(u)).^2) -4*J*omega_z(jj+1)*sin(theta).*sin(u)));
TF = islocalmin(E_minus);
a=u(TF);
if size(a)==2
Intensitysol1(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(2);
elseif size(a)==1
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
end
end
end
figure(1)
surf(omega_z, omega_y, Intensitysol1)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’)
figure(2)
surf(omega_z, omega_y, Intensitysol2)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’) Hi everyone, this is my following code with the use of map and container with if-else statement in nested for loops. I don’t understand why the error Unrecognized function or variable ‘Intensitysol1’ appears, while there is no problem for Intensitysol2. How should I fix it?
theta=0.65;
J=0.08;
for ii = 0:1:49;
omega_y(ii+1) = 0 + (0.15/100)*(ii);
end
for jj = 0:1:100;
omega_z(jj+1) = 0 -(0.15/100)*(jj);
end
valueset_omega_y_vector = 1:1:(length(omega_y));
valueset_omega_z_vector= 1:1:(length(omega_z));
M_omega_y = containers.Map(omega_y,valueset_omega_y_vector);
M_omega_z = containers.Map(omega_z, valueset_omega_z_vector);
for ii = 1:1:49
for jj = 0:1:100
u = 0 : 2*pi/1000 : 2*pi;
E_minus = 2*J*cos(theta).*cos(u) – (sqrt(omega_y(ii+1)^2 + omega_z(jj+1)^2 + 4*(J^2)*((sin(theta))^2).*((sin(u)).^2) -4*J*omega_z(jj+1)*sin(theta).*sin(u)));
TF = islocalmin(E_minus);
a=u(TF);
if size(a)==2
Intensitysol1(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(2);
elseif size(a)==1
Intensitysol2(M_omega_y(omega_y(ii+1)),M_omega_z(omega_z(jj+1)))=a(1);
end
end
end
figure(1)
surf(omega_z, omega_y, Intensitysol1)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’)
figure(2)
surf(omega_z, omega_y, Intensitysol2)
xlabel(‘omega_z’)
ylabel(‘omega_y’)
zlabel(‘k’) containers, nestedloops, finding minimum, if-else statement MATLAB Answers — New Questions
How does nufft function work in matlab?
I am trying to understand how to use nufft function. For this, I started by comparing the results of the fft and nufft transforms of a Gaussian to see if they yield the same result. I find that for a spacing in t space that is not unity, they yield different results. The exmple in MATLAB for nufft also has unit spacing between the t coordinates. Does nufft function not work for non-unit spacing? This would be a problem for me since the next step is to get the fourier transform of a gaussian with different spacings in the t space, i.e, dt varies for each element.
Thank you.
tmax = 12;
n = 2^11;
tau = 1; % Width of the gaussian pulse
dt = 2*tmax/n;
t = (-tmax:dt:tmax-dt);
fmax = 1/(2*dt);
df = 2*fmax/n;
f = -fmax:df:fmax-df;
Pulse = exp(-(t/tau).^2);
%Pulse = sin(t/tau);
fftPulse = ifftshift(fft(Pulse));
subplot(2,1,1)
plot(t,Pulse)
subplot(2,1,2)
plot(f,abs(fftPulse)); hold on;
nufftPulse = ifftshift(nufft(Pulse,t));
plot(f,abs(nufftPulse))I am trying to understand how to use nufft function. For this, I started by comparing the results of the fft and nufft transforms of a Gaussian to see if they yield the same result. I find that for a spacing in t space that is not unity, they yield different results. The exmple in MATLAB for nufft also has unit spacing between the t coordinates. Does nufft function not work for non-unit spacing? This would be a problem for me since the next step is to get the fourier transform of a gaussian with different spacings in the t space, i.e, dt varies for each element.
Thank you.
tmax = 12;
n = 2^11;
tau = 1; % Width of the gaussian pulse
dt = 2*tmax/n;
t = (-tmax:dt:tmax-dt);
fmax = 1/(2*dt);
df = 2*fmax/n;
f = -fmax:df:fmax-df;
Pulse = exp(-(t/tau).^2);
%Pulse = sin(t/tau);
fftPulse = ifftshift(fft(Pulse));
subplot(2,1,1)
plot(t,Pulse)
subplot(2,1,2)
plot(f,abs(fftPulse)); hold on;
nufftPulse = ifftshift(nufft(Pulse,t));
plot(f,abs(nufftPulse)) I am trying to understand how to use nufft function. For this, I started by comparing the results of the fft and nufft transforms of a Gaussian to see if they yield the same result. I find that for a spacing in t space that is not unity, they yield different results. The exmple in MATLAB for nufft also has unit spacing between the t coordinates. Does nufft function not work for non-unit spacing? This would be a problem for me since the next step is to get the fourier transform of a gaussian with different spacings in the t space, i.e, dt varies for each element.
Thank you.
tmax = 12;
n = 2^11;
tau = 1; % Width of the gaussian pulse
dt = 2*tmax/n;
t = (-tmax:dt:tmax-dt);
fmax = 1/(2*dt);
df = 2*fmax/n;
f = -fmax:df:fmax-df;
Pulse = exp(-(t/tau).^2);
%Pulse = sin(t/tau);
fftPulse = ifftshift(fft(Pulse));
subplot(2,1,1)
plot(t,Pulse)
subplot(2,1,2)
plot(f,abs(fftPulse)); hold on;
nufftPulse = ifftshift(nufft(Pulse,t));
plot(f,abs(nufftPulse)) nufft, nonuniform fourier trasform MATLAB Answers — New Questions
how to remove warning during code generation
hello, during the code generation some warning will apper in command window, how to turn off this, only error message can apper.hello, during the code generation some warning will apper in command window, how to turn off this, only error message can apper. hello, during the code generation some warning will apper in command window, how to turn off this, only error message can apper. simulink, code generation, warnning message MATLAB Answers — New Questions