Category: Matlab
Category Archives: Matlab
Is the “Communications System Toolbox Support Package for Xilinx FPGA-based Radio” still available?
I would like to prototype software-defined radio (SDR) systems using MATLAB & Simulink using the Xilinx Virtex-6 and Spartan-6 FPGA boards. Is there an available Support Package for Xilinx FPGA Radio?I would like to prototype software-defined radio (SDR) systems using MATLAB & Simulink using the Xilinx Virtex-6 and Spartan-6 FPGA boards. Is there an available Support Package for Xilinx FPGA Radio? I would like to prototype software-defined radio (SDR) systems using MATLAB & Simulink using the Xilinx Virtex-6 and Spartan-6 FPGA boards. Is there an available Support Package for Xilinx FPGA Radio? xilinx, fpga, support, package, communications, system, toolbox, zynq, sdr MATLAB Answers — New Questions
Loop for reading and extracting data from a single line of multiple text files.
I have the following code that I would like to put into a loop to read multiple text files.
txt = fileread(‘Test01.txt’);
temppos = strfind(txt,’Ground Temperature:’);
endpos = strfind(txt, ‘°C’);
for k = 1:numel(temppos)
section{k,:} = txt(temppos(k):endpos(k));
end
for k = 1:numel(section)
temp(k,:) = sscanf(section{k}, ‘Ground Temperature: %f’);
end
Results = table(temp, ‘VariableNames’,{‘Temp’});I have the following code that I would like to put into a loop to read multiple text files.
txt = fileread(‘Test01.txt’);
temppos = strfind(txt,’Ground Temperature:’);
endpos = strfind(txt, ‘°C’);
for k = 1:numel(temppos)
section{k,:} = txt(temppos(k):endpos(k));
end
for k = 1:numel(section)
temp(k,:) = sscanf(section{k}, ‘Ground Temperature: %f’);
end
Results = table(temp, ‘VariableNames’,{‘Temp’}); I have the following code that I would like to put into a loop to read multiple text files.
txt = fileread(‘Test01.txt’);
temppos = strfind(txt,’Ground Temperature:’);
endpos = strfind(txt, ‘°C’);
for k = 1:numel(temppos)
section{k,:} = txt(temppos(k):endpos(k));
end
for k = 1:numel(section)
temp(k,:) = sscanf(section{k}, ‘Ground Temperature: %f’);
end
Results = table(temp, ‘VariableNames’,{‘Temp’}); loop, sscanf, fid MATLAB Answers — New Questions
e^x maclaurin serie
Hello everyone, I’m very new to MATLAB. Could you help me with this question please?
How to write codes that calculate e^x by serializing the x value entered from the keyboard into a series equal to the number of terms (N) entered from the keyboard?Hello everyone, I’m very new to MATLAB. Could you help me with this question please?
How to write codes that calculate e^x by serializing the x value entered from the keyboard into a series equal to the number of terms (N) entered from the keyboard? Hello everyone, I’m very new to MATLAB. Could you help me with this question please?
How to write codes that calculate e^x by serializing the x value entered from the keyboard into a series equal to the number of terms (N) entered from the keyboard? #e^x #maclaurin #taylorseries MATLAB Answers — New Questions
How can I access or use TCP/IP sockets from MATLAB?
I want to communicate via TCP/IP using MATLAB.I want to communicate via TCP/IP using MATLAB. I want to communicate via TCP/IP using MATLAB. tcp/ip, tcpip, socket, sockets, matlab MATLAB Answers — New Questions
How do I tune a parameter in an accelerated model reference while the simulation is running?
I have a parameter in a model reference that I would like to tune while the simulation is running in accelerator mode. How do I do this?I have a parameter in a model reference that I would like to tune while the simulation is running in accelerator mode. How do I do this? I have a parameter in a model reference that I would like to tune while the simulation is running in accelerator mode. How do I do this? MATLAB Answers — New Questions
Annotation ‘arrow’ head not aligned with arrow body
Using the annotation ‘arrow’ to plot a nonlinear vector field. I have computed the components and derivatives for the two states I selected and they are held in the variables X, Y, U and V. The body of the arrow is aligned with the U V directional vectors, but all arrowheads are pointing directly to the left but and anchored on the end of the arrow line. Below is the code I’m using to create the arrow object and the handle to it, and using a 2d loop to go through my matrices.
ah = annotation(‘arrow’,…
‘headStyle’,’cback2′,’HeadLength’,headLength,’HeadWidth’,headWidth);
set(ah,’parent’,gca);
set(ah,’position’,[X(ii,ij) Y(ii,ij) LineLength*U(ii,ij) LineLength*V(ii,ij)]);
<</matlabcentral/answers/uploaded_files/123959/annotation.png>>Using the annotation ‘arrow’ to plot a nonlinear vector field. I have computed the components and derivatives for the two states I selected and they are held in the variables X, Y, U and V. The body of the arrow is aligned with the U V directional vectors, but all arrowheads are pointing directly to the left but and anchored on the end of the arrow line. Below is the code I’m using to create the arrow object and the handle to it, and using a 2d loop to go through my matrices.
ah = annotation(‘arrow’,…
‘headStyle’,’cback2′,’HeadLength’,headLength,’HeadWidth’,headWidth);
set(ah,’parent’,gca);
set(ah,’position’,[X(ii,ij) Y(ii,ij) LineLength*U(ii,ij) LineLength*V(ii,ij)]);
<</matlabcentral/answers/uploaded_files/123959/annotation.png>> Using the annotation ‘arrow’ to plot a nonlinear vector field. I have computed the components and derivatives for the two states I selected and they are held in the variables X, Y, U and V. The body of the arrow is aligned with the U V directional vectors, but all arrowheads are pointing directly to the left but and anchored on the end of the arrow line. Below is the code I’m using to create the arrow object and the handle to it, and using a 2d loop to go through my matrices.
ah = annotation(‘arrow’,…
‘headStyle’,’cback2′,’HeadLength’,headLength,’HeadWidth’,headWidth);
set(ah,’parent’,gca);
set(ah,’position’,[X(ii,ij) Y(ii,ij) LineLength*U(ii,ij) LineLength*V(ii,ij)]);
<</matlabcentral/answers/uploaded_files/123959/annotation.png>> annotation, arrow, quiver MATLAB Answers — New Questions
Why is my Mixed ANOVA including the intercept as an interaction term?
Hi there,
I have been getting different outputs from Matlab to JASP and SPSS, both of which agree that Matlab is wrong, which I think is due to the intercept being included as an interaction term in the model spec.
I have run a 2b*6w*2w Mixed ANOVA in Matlab. (Between-2=Consciousness, Within-6 = Conguency, Within-2 =Target) However I am getting the intercept as an interaction term in my ranova table:
Matlab Output
The factors Congruency and Target should be reported only as a main effects, not as an interaction with the intercept.
I’m including a JASP output so to compare the difference between the two softwares.
Could you take a look at my code, I think I’ve done something wrong in the Wilkinson notation of the model specification, and tell me how I stop it using the intercept as an interaction term.
OverallDataTable=readtable(‘Data.xlsx’)
WithinDesign=table(categorical({‘Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’,’Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’}’),categorical({‘BP’,’BP’,’BP’,’BP’,’BP’,’BP’,’O’,’O’,’O’,’O’,’O’,’O’}’), …
‘VariableNames’,{‘Congruency’,’Target’});
OverallMixedANOVA=fitrm(OverallDataTable,’BP_RH_Con-O_NF_Sub~Consciousness’,WithinDesign=WithinDesign);
OverallMixedANOVATable=ranova(OverallMixedANOVA,"WithinModel",’Congruency*Target’)
Thanks for any and all advice
DanHi there,
I have been getting different outputs from Matlab to JASP and SPSS, both of which agree that Matlab is wrong, which I think is due to the intercept being included as an interaction term in the model spec.
I have run a 2b*6w*2w Mixed ANOVA in Matlab. (Between-2=Consciousness, Within-6 = Conguency, Within-2 =Target) However I am getting the intercept as an interaction term in my ranova table:
Matlab Output
The factors Congruency and Target should be reported only as a main effects, not as an interaction with the intercept.
I’m including a JASP output so to compare the difference between the two softwares.
Could you take a look at my code, I think I’ve done something wrong in the Wilkinson notation of the model specification, and tell me how I stop it using the intercept as an interaction term.
OverallDataTable=readtable(‘Data.xlsx’)
WithinDesign=table(categorical({‘Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’,’Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’}’),categorical({‘BP’,’BP’,’BP’,’BP’,’BP’,’BP’,’O’,’O’,’O’,’O’,’O’,’O’}’), …
‘VariableNames’,{‘Congruency’,’Target’});
OverallMixedANOVA=fitrm(OverallDataTable,’BP_RH_Con-O_NF_Sub~Consciousness’,WithinDesign=WithinDesign);
OverallMixedANOVATable=ranova(OverallMixedANOVA,"WithinModel",’Congruency*Target’)
Thanks for any and all advice
Dan Hi there,
I have been getting different outputs from Matlab to JASP and SPSS, both of which agree that Matlab is wrong, which I think is due to the intercept being included as an interaction term in the model spec.
I have run a 2b*6w*2w Mixed ANOVA in Matlab. (Between-2=Consciousness, Within-6 = Conguency, Within-2 =Target) However I am getting the intercept as an interaction term in my ranova table:
Matlab Output
The factors Congruency and Target should be reported only as a main effects, not as an interaction with the intercept.
I’m including a JASP output so to compare the difference between the two softwares.
Could you take a look at my code, I think I’ve done something wrong in the Wilkinson notation of the model specification, and tell me how I stop it using the intercept as an interaction term.
OverallDataTable=readtable(‘Data.xlsx’)
WithinDesign=table(categorical({‘Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’,’Related Hand’,’Related Foot’,’Unrelated Hand’,’Unrelated Foot’, …
‘Neutral Hand’,’Neutral Foot’}’),categorical({‘BP’,’BP’,’BP’,’BP’,’BP’,’BP’,’O’,’O’,’O’,’O’,’O’,’O’}’), …
‘VariableNames’,{‘Congruency’,’Target’});
OverallMixedANOVA=fitrm(OverallDataTable,’BP_RH_Con-O_NF_Sub~Consciousness’,WithinDesign=WithinDesign);
OverallMixedANOVATable=ranova(OverallMixedANOVA,"WithinModel",’Congruency*Target’)
Thanks for any and all advice
Dan fitrm, statistics, mixed anova, ranova, wilkinson notation MATLAB Answers — New Questions
Targetlink error: TlCScaledAbsMinMaxConverter 1223
Hello,
when I try to generate the code of a model (Matlab 2016b, TargetLink 4.2) I got the following Fatal error:
Fatal #10008: model path
Internal error.
Error code: TlCScaledAbsMinMaxConverter 1223
NB: A colleague of mine can successfully generate from this model. I can successfully generate code from other models.
I can’t find a solution because the description of the error is generic and the guide is not helpful.
Thank you in advanceHello,
when I try to generate the code of a model (Matlab 2016b, TargetLink 4.2) I got the following Fatal error:
Fatal #10008: model path
Internal error.
Error code: TlCScaledAbsMinMaxConverter 1223
NB: A colleague of mine can successfully generate from this model. I can successfully generate code from other models.
I can’t find a solution because the description of the error is generic and the guide is not helpful.
Thank you in advance Hello,
when I try to generate the code of a model (Matlab 2016b, TargetLink 4.2) I got the following Fatal error:
Fatal #10008: model path
Internal error.
Error code: TlCScaledAbsMinMaxConverter 1223
NB: A colleague of mine can successfully generate from this model. I can successfully generate code from other models.
I can’t find a solution because the description of the error is generic and the guide is not helpful.
Thank you in advance targetlink, error, generation MATLAB Answers — New Questions
I keep getting the error “Error: File: builtin.m Line: 1 Column: 24 Invalid text character…”. How do I fix this?
Hi,
The full error is:
"Error: File: builtin.m Line: 1 Column: 24
Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII characters."
I get it whenever I try to do anything, including close Matlab. The file name changes slightly depending on what I do: for example, when I try to open a new file, I get the following error:
"Error in matlab.unittest.internal.ui.toolstrip.getFileInfoForToolstrip (line 8)
isClassBasedTest = false;",
preceded by the above text with "false.m" as the file name.
I think the problem started when I tried to set the path? I got the following error:
"Unable to run P-code file. The file header is damaged.
Error in pathtool (line 13)
isDesktop = desktop(‘-inuse’);"
But I’m not sure. Any help that you can give me would be appreciated!Hi,
The full error is:
"Error: File: builtin.m Line: 1 Column: 24
Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII characters."
I get it whenever I try to do anything, including close Matlab. The file name changes slightly depending on what I do: for example, when I try to open a new file, I get the following error:
"Error in matlab.unittest.internal.ui.toolstrip.getFileInfoForToolstrip (line 8)
isClassBasedTest = false;",
preceded by the above text with "false.m" as the file name.
I think the problem started when I tried to set the path? I got the following error:
"Unable to run P-code file. The file header is damaged.
Error in pathtool (line 13)
isDesktop = desktop(‘-inuse’);"
But I’m not sure. Any help that you can give me would be appreciated! Hi,
The full error is:
"Error: File: builtin.m Line: 1 Column: 24
Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII characters."
I get it whenever I try to do anything, including close Matlab. The file name changes slightly depending on what I do: for example, when I try to open a new file, I get the following error:
"Error in matlab.unittest.internal.ui.toolstrip.getFileInfoForToolstrip (line 8)
isClassBasedTest = false;",
preceded by the above text with "false.m" as the file name.
I think the problem started when I tried to set the path? I got the following error:
"Unable to run P-code file. The file header is damaged.
Error in pathtool (line 13)
isDesktop = desktop(‘-inuse’);"
But I’m not sure. Any help that you can give me would be appreciated! matlab, set path MATLAB Answers — New Questions
Simscape multibody reinforced learning: unpossible to run examples
I was trying to run some examples of training on simscape using reinforced learning, but I’m not able to run them. They look to be by far excessiive for my machine. Anybody shares my issues?I was trying to run some examples of training on simscape using reinforced learning, but I’m not able to run them. They look to be by far excessiive for my machine. Anybody shares my issues? I was trying to run some examples of training on simscape using reinforced learning, but I’m not able to run them. They look to be by far excessiive for my machine. Anybody shares my issues? simscape, reinforced learning MATLAB Answers — New Questions
MATLAB stalls after running script
I have a pretty large script that analyzes a somewhat large data file (~5gbs). My script works fine when I first run it but then when I go to run a codeblock or even just try to get the output from a single simple variable in the command window AFTER I loaded everything into my workspace, MATLAB will stall for a minute or even more before starting to run whatever command I gave it. I’ve been monitoring my PC resources and it doesn’t seem like I am running out of RAM or anything (working with 64gbs). I even went through and cleared many larger variables that were not needed for later parts of the script and the problem persists. I do not recieve any errors, it is just very slow to do simple things. Once it starts executing the command, it runs at the expected speed (I’ve verfied with some manual progress bars I coded in).
The data that I load is from a single .MAT file which has a structure in it with all of my data. I’ve also ran this script on 3 other PCs and had the same issue.I have a pretty large script that analyzes a somewhat large data file (~5gbs). My script works fine when I first run it but then when I go to run a codeblock or even just try to get the output from a single simple variable in the command window AFTER I loaded everything into my workspace, MATLAB will stall for a minute or even more before starting to run whatever command I gave it. I’ve been monitoring my PC resources and it doesn’t seem like I am running out of RAM or anything (working with 64gbs). I even went through and cleared many larger variables that were not needed for later parts of the script and the problem persists. I do not recieve any errors, it is just very slow to do simple things. Once it starts executing the command, it runs at the expected speed (I’ve verfied with some manual progress bars I coded in).
The data that I load is from a single .MAT file which has a structure in it with all of my data. I’ve also ran this script on 3 other PCs and had the same issue. I have a pretty large script that analyzes a somewhat large data file (~5gbs). My script works fine when I first run it but then when I go to run a codeblock or even just try to get the output from a single simple variable in the command window AFTER I loaded everything into my workspace, MATLAB will stall for a minute or even more before starting to run whatever command I gave it. I’ve been monitoring my PC resources and it doesn’t seem like I am running out of RAM or anything (working with 64gbs). I even went through and cleared many larger variables that were not needed for later parts of the script and the problem persists. I do not recieve any errors, it is just very slow to do simple things. Once it starts executing the command, it runs at the expected speed (I’ve verfied with some manual progress bars I coded in).
The data that I load is from a single .MAT file which has a structure in it with all of my data. I’ve also ran this script on 3 other PCs and had the same issue. structures MATLAB Answers — New Questions
How to change units in Bode Diagram?
I want to change the units of frequency and magnitude in the Bode Diagram, how can I do this?I want to change the units of frequency and magnitude in the Bode Diagram, how can I do this? I want to change the units of frequency and magnitude in the Bode Diagram, how can I do this? change, bode, diagram, units, properties, problematically, command, line, figure, setoptions MATLAB Answers — New Questions
How to Change Line Color on Mouse Click Without Disabling Pan and Zoom in MATLAB?
I’m working on a MATLAB plot where I want to achieve the following functionality:
Change the color of a line when it’s clicked.
Enable panning by dragging while clicking off the line.
Enable zooming using the scroll wheel.
Here’s the simple code I’m using:
% Plotting a simple line
h = plot([0,1],[0,1],’LineWidth’,3);
% Setting the ButtonDownFcn to change line color (placeholder code)
h.ButtonDownFcn = @(~,~) disp(h);
In this example, clicking on the line displays its handle h in the Command Window, which is a placeholder for my actual code to change the line color.
The Problem:
Assigning a ButtonDownFcn to the line object seems to override MATLAB’s built-in pan and zoom functionalities. After setting the ButtonDownFcn, I’m unable to pan by clicking and dragging off the line, and the scroll wheel zoom no longer works. It appears that the custom callback interferes with the default interactive behaviors, even when I’m not interacting directly with the line.
My Questions:
Why does setting the ButtonDownFcn on the line object disable panning and zooming, even when interacting off the line?
Is there a way to have both the custom click behavior (changing the line color when clicked) and retain the default pan and zoom functionalities when interacting elsewhere on the plot?I’m working on a MATLAB plot where I want to achieve the following functionality:
Change the color of a line when it’s clicked.
Enable panning by dragging while clicking off the line.
Enable zooming using the scroll wheel.
Here’s the simple code I’m using:
% Plotting a simple line
h = plot([0,1],[0,1],’LineWidth’,3);
% Setting the ButtonDownFcn to change line color (placeholder code)
h.ButtonDownFcn = @(~,~) disp(h);
In this example, clicking on the line displays its handle h in the Command Window, which is a placeholder for my actual code to change the line color.
The Problem:
Assigning a ButtonDownFcn to the line object seems to override MATLAB’s built-in pan and zoom functionalities. After setting the ButtonDownFcn, I’m unable to pan by clicking and dragging off the line, and the scroll wheel zoom no longer works. It appears that the custom callback interferes with the default interactive behaviors, even when I’m not interacting directly with the line.
My Questions:
Why does setting the ButtonDownFcn on the line object disable panning and zooming, even when interacting off the line?
Is there a way to have both the custom click behavior (changing the line color when clicked) and retain the default pan and zoom functionalities when interacting elsewhere on the plot? I’m working on a MATLAB plot where I want to achieve the following functionality:
Change the color of a line when it’s clicked.
Enable panning by dragging while clicking off the line.
Enable zooming using the scroll wheel.
Here’s the simple code I’m using:
% Plotting a simple line
h = plot([0,1],[0,1],’LineWidth’,3);
% Setting the ButtonDownFcn to change line color (placeholder code)
h.ButtonDownFcn = @(~,~) disp(h);
In this example, clicking on the line displays its handle h in the Command Window, which is a placeholder for my actual code to change the line color.
The Problem:
Assigning a ButtonDownFcn to the line object seems to override MATLAB’s built-in pan and zoom functionalities. After setting the ButtonDownFcn, I’m unable to pan by clicking and dragging off the line, and the scroll wheel zoom no longer works. It appears that the custom callback interferes with the default interactive behaviors, even when I’m not interacting directly with the line.
My Questions:
Why does setting the ButtonDownFcn on the line object disable panning and zooming, even when interacting off the line?
Is there a way to have both the custom click behavior (changing the line color when clicked) and retain the default pan and zoom functionalities when interacting elsewhere on the plot? callback, plot MATLAB Answers — New Questions
calculate angles for walking robot
I am studying the model of a walking robot from the project https://www.mathworks.com/matlabcentral/fileexchange/64227-matlab-and-simulink-robotics-arena-walking-robot, if I increase the length and width of the legs and body, and also add arms and a head block, then the robot takes only one step and falls, as I understand it, for the changed parameters it is necessary to calculate the angles again, how can I do this?
how did the authors of the project calculate the variables "jAngsL", "jAngR", "siminL", "siminR"?I am studying the model of a walking robot from the project https://www.mathworks.com/matlabcentral/fileexchange/64227-matlab-and-simulink-robotics-arena-walking-robot, if I increase the length and width of the legs and body, and also add arms and a head block, then the robot takes only one step and falls, as I understand it, for the changed parameters it is necessary to calculate the angles again, how can I do this?
how did the authors of the project calculate the variables "jAngsL", "jAngR", "siminL", "siminR"? I am studying the model of a walking robot from the project https://www.mathworks.com/matlabcentral/fileexchange/64227-matlab-and-simulink-robotics-arena-walking-robot, if I increase the length and width of the legs and body, and also add arms and a head block, then the robot takes only one step and falls, as I understand it, for the changed parameters it is necessary to calculate the angles again, how can I do this?
how did the authors of the project calculate the variables "jAngsL", "jAngR", "siminL", "siminR"? roboticsarena, walkingrobot, bipedalrobot, inversekinematics, simulink MATLAB Answers — New Questions
Can anyone help me with my code? I want to apply the windowing function to my code with a duration of 200 ms to observe the leakage.
function [y, signalT, notch_intensity] = signalfunccycle(Gridlength, startfreq, endfreq, notchstart1, notchend1, datalength)
close all;
clear all;
PIx2 = 2 * pi; % used to calculate the frequency values of the output signal
fstart = 0;
Gridlength = 200e-3;
startfreq = 40e3;
endfreq = 200e3;
stimeStep = 5e-8;
datalength = round(Gridlength / stimeStep);
notchstart1 = 116000;
notchend1 = 119000;
dataN = datalength;
Stimelength = Gridlength;
fend = 10^6;
Fs = dataN / Gridlength;
NFFT = dataN; % Number of points used in the FFT analysis
fstep = (Fs – fstart) / NFFT; % Point step
T = 1 / Fs;
Stime = linspace(0, Stimelength, dataN);
t = (0:dataN-1) * T; % Length of time
signal = zeros(1, length(t));
f1 = notchstart1;
f2 = notchend1;
f3 = notchstart1;
f4 = notchend1;
for freq = startfreq:0.5*10^3:endfreq
if (f1 <= freq && freq <= f2) || (f3 <= freq && freq <= f4)
continue;
end
signal = sin(PIx2 * freq * t + pi) + signal;
end
%% Time-domain signal graphs
figure(1);
plot(Stime, signal);
grid on;
title(‘signal’);
xlabel(‘time’);
ylabel(‘amplitude’);
%% FFT
fMax = NFFT / 2 + 1; % The maximum frequency to plot
signalFFT0 = fft(signal, NFFT); % FFT of the signal
signalFFT_phase = angle(fft(signal, NFFT)); % Phase of the FFT result
signalFFT = abs(fft(signal, NFFT)); % Absolute value (modulus) of the FFT result
signalFFTShow = 2 * signalFFT / dataN; % Actual amplitude values
signalFFTShow(1) = signalFFTShow(1) / 2; % DC component
f = Fs / 2 * linspace(0, 1, fMax); % Actual frequencies
% Plot FFT of the signal
figure(2);
plot(f, signalFFTShow(1:fMax), ‘r’, ‘LineWidth’, 3); % Red color, line width set to 3
grid on; % Display grid lines
title(‘FFT Signal’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
%% Phase function modulation
signalstart = startfreq;
signalend = endfreq;
Istart = round(signalstart / fstep);
Iend = round(signalend / fstep);
Itotal = Iend – Istart;
N1start1 = round(f1);
N1end1 = round(f2);
N1start2 = round(f3);
N1end2 = round(f4);
signalphase(1:NFFT) = 0;
for I = 1:NFFT
if (I <= N1end1 && I >= N1start1) || (I <= N1end2 && I >= N1start2)
signalphase(I) = 0;
else
signalphase(I) = pi / 2 * (I – Istart) + 1 * pi / Itotal / 2 * (I – Istart)^2;
end
end
signalF = 1/2 * signalFFTShow .* exp(1i * (signalphase + signalFFT_phase));
signalT = ifft(NFFT * signalF);
t1 = (0:NFFT-1) * T;
%% Phase spectrogram
x1 = 1:NFFT;
figure(3);
plot(x1, signalphase)
xlabel(‘frequency’);
ylabel(‘Phase’);
title(‘Phase spectrum’);
%% Signal waveform after modulation
signaltime = (0:NFFT-1) * T;
figure(4);
plot(signaltime, real(signalT));
xlabel(‘time’);
ylabel(‘amplitude’);
signalT_real = real(signalT);
savefile = ‘signalT_real.txt’;
x = Stime’;
y = signalT_real’;
save(savefile, ‘x’, ‘y’, ‘-ASCII’)
%% STFT Calculation
NN = 10;
win_size = round(datalength / NN);
overlap = 0;
fft_size = win_size * 2 + 1;
stft_result = [];
for i = 1:win_size*(1-overlap):length(signalT)-win_size
window = signalT(i:i+win_size-1);
fft_result = fft(window, fft_size+1);
stft_result = [stft_result; abs(fft_result(1:fft_size))];
end
time_axis = linspace(0, Gridlength, size(stft_result, 1));
freq_axis = linspace(fstart, fend, fft_size);
% Extract intensity for notch frequencies (116 to 119 kHz)
notch_indices = find(freq_axis >= 116000 & freq_axis <= 119000);
notch_intensity = mean(stft_result(:, notch_indices), 2);
% Plot the STFT spectrogram
figure(5);
imagesc(time_axis * 1000, freq_axis / 1000, stft_result.’);
axis([Gridlength * 950 Gridlength * 1050 110e3 / 1000 125e3 / 1000]);
colorbar;
ylabel(‘Frequency (kHz)’);
xlabel(‘Time (ms)’);
% % Plot the intensity over time for the notch frequencies
% figure(6);
% plot(time_axis * 1000, notch_intensity, ‘LineWidth’, 2);
% xlabel(‘Time (ms)’);
% ylabel(‘Intensity’);
% title(‘Intensity at Notch Frequencies (116 to 119 kHz)’);
% grid on;
endfunction [y, signalT, notch_intensity] = signalfunccycle(Gridlength, startfreq, endfreq, notchstart1, notchend1, datalength)
close all;
clear all;
PIx2 = 2 * pi; % used to calculate the frequency values of the output signal
fstart = 0;
Gridlength = 200e-3;
startfreq = 40e3;
endfreq = 200e3;
stimeStep = 5e-8;
datalength = round(Gridlength / stimeStep);
notchstart1 = 116000;
notchend1 = 119000;
dataN = datalength;
Stimelength = Gridlength;
fend = 10^6;
Fs = dataN / Gridlength;
NFFT = dataN; % Number of points used in the FFT analysis
fstep = (Fs – fstart) / NFFT; % Point step
T = 1 / Fs;
Stime = linspace(0, Stimelength, dataN);
t = (0:dataN-1) * T; % Length of time
signal = zeros(1, length(t));
f1 = notchstart1;
f2 = notchend1;
f3 = notchstart1;
f4 = notchend1;
for freq = startfreq:0.5*10^3:endfreq
if (f1 <= freq && freq <= f2) || (f3 <= freq && freq <= f4)
continue;
end
signal = sin(PIx2 * freq * t + pi) + signal;
end
%% Time-domain signal graphs
figure(1);
plot(Stime, signal);
grid on;
title(‘signal’);
xlabel(‘time’);
ylabel(‘amplitude’);
%% FFT
fMax = NFFT / 2 + 1; % The maximum frequency to plot
signalFFT0 = fft(signal, NFFT); % FFT of the signal
signalFFT_phase = angle(fft(signal, NFFT)); % Phase of the FFT result
signalFFT = abs(fft(signal, NFFT)); % Absolute value (modulus) of the FFT result
signalFFTShow = 2 * signalFFT / dataN; % Actual amplitude values
signalFFTShow(1) = signalFFTShow(1) / 2; % DC component
f = Fs / 2 * linspace(0, 1, fMax); % Actual frequencies
% Plot FFT of the signal
figure(2);
plot(f, signalFFTShow(1:fMax), ‘r’, ‘LineWidth’, 3); % Red color, line width set to 3
grid on; % Display grid lines
title(‘FFT Signal’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
%% Phase function modulation
signalstart = startfreq;
signalend = endfreq;
Istart = round(signalstart / fstep);
Iend = round(signalend / fstep);
Itotal = Iend – Istart;
N1start1 = round(f1);
N1end1 = round(f2);
N1start2 = round(f3);
N1end2 = round(f4);
signalphase(1:NFFT) = 0;
for I = 1:NFFT
if (I <= N1end1 && I >= N1start1) || (I <= N1end2 && I >= N1start2)
signalphase(I) = 0;
else
signalphase(I) = pi / 2 * (I – Istart) + 1 * pi / Itotal / 2 * (I – Istart)^2;
end
end
signalF = 1/2 * signalFFTShow .* exp(1i * (signalphase + signalFFT_phase));
signalT = ifft(NFFT * signalF);
t1 = (0:NFFT-1) * T;
%% Phase spectrogram
x1 = 1:NFFT;
figure(3);
plot(x1, signalphase)
xlabel(‘frequency’);
ylabel(‘Phase’);
title(‘Phase spectrum’);
%% Signal waveform after modulation
signaltime = (0:NFFT-1) * T;
figure(4);
plot(signaltime, real(signalT));
xlabel(‘time’);
ylabel(‘amplitude’);
signalT_real = real(signalT);
savefile = ‘signalT_real.txt’;
x = Stime’;
y = signalT_real’;
save(savefile, ‘x’, ‘y’, ‘-ASCII’)
%% STFT Calculation
NN = 10;
win_size = round(datalength / NN);
overlap = 0;
fft_size = win_size * 2 + 1;
stft_result = [];
for i = 1:win_size*(1-overlap):length(signalT)-win_size
window = signalT(i:i+win_size-1);
fft_result = fft(window, fft_size+1);
stft_result = [stft_result; abs(fft_result(1:fft_size))];
end
time_axis = linspace(0, Gridlength, size(stft_result, 1));
freq_axis = linspace(fstart, fend, fft_size);
% Extract intensity for notch frequencies (116 to 119 kHz)
notch_indices = find(freq_axis >= 116000 & freq_axis <= 119000);
notch_intensity = mean(stft_result(:, notch_indices), 2);
% Plot the STFT spectrogram
figure(5);
imagesc(time_axis * 1000, freq_axis / 1000, stft_result.’);
axis([Gridlength * 950 Gridlength * 1050 110e3 / 1000 125e3 / 1000]);
colorbar;
ylabel(‘Frequency (kHz)’);
xlabel(‘Time (ms)’);
% % Plot the intensity over time for the notch frequencies
% figure(6);
% plot(time_axis * 1000, notch_intensity, ‘LineWidth’, 2);
% xlabel(‘Time (ms)’);
% ylabel(‘Intensity’);
% title(‘Intensity at Notch Frequencies (116 to 119 kHz)’);
% grid on;
end function [y, signalT, notch_intensity] = signalfunccycle(Gridlength, startfreq, endfreq, notchstart1, notchend1, datalength)
close all;
clear all;
PIx2 = 2 * pi; % used to calculate the frequency values of the output signal
fstart = 0;
Gridlength = 200e-3;
startfreq = 40e3;
endfreq = 200e3;
stimeStep = 5e-8;
datalength = round(Gridlength / stimeStep);
notchstart1 = 116000;
notchend1 = 119000;
dataN = datalength;
Stimelength = Gridlength;
fend = 10^6;
Fs = dataN / Gridlength;
NFFT = dataN; % Number of points used in the FFT analysis
fstep = (Fs – fstart) / NFFT; % Point step
T = 1 / Fs;
Stime = linspace(0, Stimelength, dataN);
t = (0:dataN-1) * T; % Length of time
signal = zeros(1, length(t));
f1 = notchstart1;
f2 = notchend1;
f3 = notchstart1;
f4 = notchend1;
for freq = startfreq:0.5*10^3:endfreq
if (f1 <= freq && freq <= f2) || (f3 <= freq && freq <= f4)
continue;
end
signal = sin(PIx2 * freq * t + pi) + signal;
end
%% Time-domain signal graphs
figure(1);
plot(Stime, signal);
grid on;
title(‘signal’);
xlabel(‘time’);
ylabel(‘amplitude’);
%% FFT
fMax = NFFT / 2 + 1; % The maximum frequency to plot
signalFFT0 = fft(signal, NFFT); % FFT of the signal
signalFFT_phase = angle(fft(signal, NFFT)); % Phase of the FFT result
signalFFT = abs(fft(signal, NFFT)); % Absolute value (modulus) of the FFT result
signalFFTShow = 2 * signalFFT / dataN; % Actual amplitude values
signalFFTShow(1) = signalFFTShow(1) / 2; % DC component
f = Fs / 2 * linspace(0, 1, fMax); % Actual frequencies
% Plot FFT of the signal
figure(2);
plot(f, signalFFTShow(1:fMax), ‘r’, ‘LineWidth’, 3); % Red color, line width set to 3
grid on; % Display grid lines
title(‘FFT Signal’);
xlabel(‘Frequency’);
ylabel(‘Amplitude’);
%% Phase function modulation
signalstart = startfreq;
signalend = endfreq;
Istart = round(signalstart / fstep);
Iend = round(signalend / fstep);
Itotal = Iend – Istart;
N1start1 = round(f1);
N1end1 = round(f2);
N1start2 = round(f3);
N1end2 = round(f4);
signalphase(1:NFFT) = 0;
for I = 1:NFFT
if (I <= N1end1 && I >= N1start1) || (I <= N1end2 && I >= N1start2)
signalphase(I) = 0;
else
signalphase(I) = pi / 2 * (I – Istart) + 1 * pi / Itotal / 2 * (I – Istart)^2;
end
end
signalF = 1/2 * signalFFTShow .* exp(1i * (signalphase + signalFFT_phase));
signalT = ifft(NFFT * signalF);
t1 = (0:NFFT-1) * T;
%% Phase spectrogram
x1 = 1:NFFT;
figure(3);
plot(x1, signalphase)
xlabel(‘frequency’);
ylabel(‘Phase’);
title(‘Phase spectrum’);
%% Signal waveform after modulation
signaltime = (0:NFFT-1) * T;
figure(4);
plot(signaltime, real(signalT));
xlabel(‘time’);
ylabel(‘amplitude’);
signalT_real = real(signalT);
savefile = ‘signalT_real.txt’;
x = Stime’;
y = signalT_real’;
save(savefile, ‘x’, ‘y’, ‘-ASCII’)
%% STFT Calculation
NN = 10;
win_size = round(datalength / NN);
overlap = 0;
fft_size = win_size * 2 + 1;
stft_result = [];
for i = 1:win_size*(1-overlap):length(signalT)-win_size
window = signalT(i:i+win_size-1);
fft_result = fft(window, fft_size+1);
stft_result = [stft_result; abs(fft_result(1:fft_size))];
end
time_axis = linspace(0, Gridlength, size(stft_result, 1));
freq_axis = linspace(fstart, fend, fft_size);
% Extract intensity for notch frequencies (116 to 119 kHz)
notch_indices = find(freq_axis >= 116000 & freq_axis <= 119000);
notch_intensity = mean(stft_result(:, notch_indices), 2);
% Plot the STFT spectrogram
figure(5);
imagesc(time_axis * 1000, freq_axis / 1000, stft_result.’);
axis([Gridlength * 950 Gridlength * 1050 110e3 / 1000 125e3 / 1000]);
colorbar;
ylabel(‘Frequency (kHz)’);
xlabel(‘Time (ms)’);
% % Plot the intensity over time for the notch frequencies
% figure(6);
% plot(time_axis * 1000, notch_intensity, ‘LineWidth’, 2);
% xlabel(‘Time (ms)’);
% ylabel(‘Intensity’);
% title(‘Intensity at Notch Frequencies (116 to 119 kHz)’);
% grid on;
end matlab code MATLAB Answers — New Questions
Is it possible to realize such loop in MATLAB?
Good day, everyone!
For example, we have some x variable.
Is it possible to realize such loop (using "for") to get these results?
1-st iteration: x-1
2-nd iteration: (x-1)*(x-2)
3-rd iteration: (x-1)*(x-2)*(x-3)
etc.Good day, everyone!
For example, we have some x variable.
Is it possible to realize such loop (using "for") to get these results?
1-st iteration: x-1
2-nd iteration: (x-1)*(x-2)
3-rd iteration: (x-1)*(x-2)*(x-3)
etc. Good day, everyone!
For example, we have some x variable.
Is it possible to realize such loop (using "for") to get these results?
1-st iteration: x-1
2-nd iteration: (x-1)*(x-2)
3-rd iteration: (x-1)*(x-2)*(x-3)
etc. loops MATLAB Answers — New Questions
I have a question relate to Gauss seidel method
Implement the Gauss-Seidel method for solving a system of linear equations from scratch in MATLAB and walk me through your thought process in constructing the code. Additionally, demonstrate that your implementation works by applying it to the following system. 2x +3y −z =7 , x −2y+4z =1 , 3x +y+2z =8
%Gauss seidel
A=input(‘Enter a co-efficient matrix A: ‘);
B=input(‘Enter source vector B: ‘);
P=input(‘Enter initial guess vector: ‘);
n=input(‘Enter number of iterations: ‘);
e=input(‘Enter tolerance: ‘);
N=length(B);
X=zeros(N,1);
Y=zeros(N,1); %for stopping criteria
for j=1:n
for i=1:N
x(i)=(B(i)/A(i,i))-(A(i,[1:i-1,i+1:N])*P([1:i-1,i+1:N]))/A(i,i);
P(i)=X(i);
end
fprintf(‘Iterations no %d n’ ,j)
X
if abs (Y-X)<e
break
end
Y=X;
end
This is my code is this correct? please help meImplement the Gauss-Seidel method for solving a system of linear equations from scratch in MATLAB and walk me through your thought process in constructing the code. Additionally, demonstrate that your implementation works by applying it to the following system. 2x +3y −z =7 , x −2y+4z =1 , 3x +y+2z =8
%Gauss seidel
A=input(‘Enter a co-efficient matrix A: ‘);
B=input(‘Enter source vector B: ‘);
P=input(‘Enter initial guess vector: ‘);
n=input(‘Enter number of iterations: ‘);
e=input(‘Enter tolerance: ‘);
N=length(B);
X=zeros(N,1);
Y=zeros(N,1); %for stopping criteria
for j=1:n
for i=1:N
x(i)=(B(i)/A(i,i))-(A(i,[1:i-1,i+1:N])*P([1:i-1,i+1:N]))/A(i,i);
P(i)=X(i);
end
fprintf(‘Iterations no %d n’ ,j)
X
if abs (Y-X)<e
break
end
Y=X;
end
This is my code is this correct? please help me Implement the Gauss-Seidel method for solving a system of linear equations from scratch in MATLAB and walk me through your thought process in constructing the code. Additionally, demonstrate that your implementation works by applying it to the following system. 2x +3y −z =7 , x −2y+4z =1 , 3x +y+2z =8
%Gauss seidel
A=input(‘Enter a co-efficient matrix A: ‘);
B=input(‘Enter source vector B: ‘);
P=input(‘Enter initial guess vector: ‘);
n=input(‘Enter number of iterations: ‘);
e=input(‘Enter tolerance: ‘);
N=length(B);
X=zeros(N,1);
Y=zeros(N,1); %for stopping criteria
for j=1:n
for i=1:N
x(i)=(B(i)/A(i,i))-(A(i,[1:i-1,i+1:N])*P([1:i-1,i+1:N]))/A(i,i);
P(i)=X(i);
end
fprintf(‘Iterations no %d n’ ,j)
X
if abs (Y-X)<e
break
end
Y=X;
end
This is my code is this correct? please help me @wantquickhelp MATLAB Answers — New Questions
In a table, when I try assigning a value to a new column based on some criteria, I get error that “assignment to elements using simple assignment statement is not supported”
I have a table for which I create an index where the values in a particular column are not NaN. I then try to use this index to create an entry into a new array and replace the values at the corresponding index (preloaded with ‘0000’) with ‘0001’. I will then add this array to the table as a new column.
My intention is to fill the corresponding indx in the column with ‘0001’, if the value in the newTable.PEM1_GA_Current_Estimate_Error a valid number (not NaN).
PEM1b =’0001′;
PEM2b =’0010′;
PEM3b = ‘0100’;
PEM4 = ‘1000’;
temp={};
indx=(find(newTable.PEM1_GA_Current_Estimate_Error ~= NaN))
temp ={repmat(‘0000’,size(newTable,1),1)}
temp{indx} = PEM1b
%…and add this array as a new column to the table
the last assigment in the code above generates this error:
Assigning to 2609 elements using a simple assignment statement is not supported. Consider using comma-separated list assignment.
I don’t think I should need a for loop to iterate through each row and replace the value at the "indx" location –what am I doing wrong?
I included the data….thank you.I have a table for which I create an index where the values in a particular column are not NaN. I then try to use this index to create an entry into a new array and replace the values at the corresponding index (preloaded with ‘0000’) with ‘0001’. I will then add this array to the table as a new column.
My intention is to fill the corresponding indx in the column with ‘0001’, if the value in the newTable.PEM1_GA_Current_Estimate_Error a valid number (not NaN).
PEM1b =’0001′;
PEM2b =’0010′;
PEM3b = ‘0100’;
PEM4 = ‘1000’;
temp={};
indx=(find(newTable.PEM1_GA_Current_Estimate_Error ~= NaN))
temp ={repmat(‘0000’,size(newTable,1),1)}
temp{indx} = PEM1b
%…and add this array as a new column to the table
the last assigment in the code above generates this error:
Assigning to 2609 elements using a simple assignment statement is not supported. Consider using comma-separated list assignment.
I don’t think I should need a for loop to iterate through each row and replace the value at the "indx" location –what am I doing wrong?
I included the data….thank you. I have a table for which I create an index where the values in a particular column are not NaN. I then try to use this index to create an entry into a new array and replace the values at the corresponding index (preloaded with ‘0000’) with ‘0001’. I will then add this array to the table as a new column.
My intention is to fill the corresponding indx in the column with ‘0001’, if the value in the newTable.PEM1_GA_Current_Estimate_Error a valid number (not NaN).
PEM1b =’0001′;
PEM2b =’0010′;
PEM3b = ‘0100’;
PEM4 = ‘1000’;
temp={};
indx=(find(newTable.PEM1_GA_Current_Estimate_Error ~= NaN))
temp ={repmat(‘0000’,size(newTable,1),1)}
temp{indx} = PEM1b
%…and add this array as a new column to the table
the last assigment in the code above generates this error:
Assigning to 2609 elements using a simple assignment statement is not supported. Consider using comma-separated list assignment.
I don’t think I should need a for loop to iterate through each row and replace the value at the "indx" location –what am I doing wrong?
I included the data….thank you. cell array, indexing MATLAB Answers — New Questions
i get black image danoise when the simulation finish what is the problem in the code ?
clc
clear all
close all
image_org=imread(‘C:UserspcOneDriveDesktopmemoirechapitre 3image for test’,’JPG’);
% Gaussian white noise
X = double(image_org) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.01);%NG=gaussian noise
figure(1);subplot(231); imshow(image_org);title (‘image org’)
subplot(233); imshow(NG) ; title (‘Gaussian additive noise’)
NG_gray = rgb2gray(NG);
%averaging filter
f_m = fspecial (‘average’, 3)%f_m=averaging filter
NGmoy = imfilter (NG, f_m,’replicate’);
%gaussian filter
f_g = fspecial (‘gaussian’,3,0.8)%f_g=gaussian filter
NGg = imfilter(NG,f_g,’replicate’);
%median filter
NGmed = medfilt2( NG_gray ,[3 3]);
%the show
subplot(234); imshow(NGmoy);title(‘ avraging Filter ‘)
subplot(235); imshow(NGg);title(‘ gaussien Filtre ‘)
subplot(236); imshow(NGmed);title(‘ median Filtre’)
%PSNR
EQMb=mean2((X-NG).^2 );PSNRb=-10*log10(EQMb);
EQMmoy=mean2( (NG-NGmoy).^2 );PSNRmoy=-10*log10(EQMmoy);
EQMg=mean2( (NG-NGg).^2 );PSNRg=-10*log10(EQMg);
EQMmed=mean2( (NG_gray-NGmed).^2 );PSNRmed=-10*log10(EQMmed);
% Resize the original image to match the input size of the CNN
image_resized = imresize(image_org, [299 450]);
% Add Gaussian noise to the original image
X = double(image_resized) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.03); % Add Gaussian noise
% Display the original and noisy images
figure(1);
subplot(1, 2, 1);
imshow(image_resized);
title(‘Original Image’);
subplot(1, 2, 2);
imshow(NG);
title(‘Noisy Image’);
% Prepare data for training (noisy images as input, original images as target)
inputData = NG; % Noisy images
targetData = X; % Original clean images
% Define the CNN architecture for image denoising
layers = [
imageInputLayer([299 450 3]) % Input layer with the size of the input images
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Convolutional layer with 64 filters of size 3×3
reluLayer % ReLU activation layer
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Another convolutional layer
reluLayer % ReLU activation layer
convolution2dLayer(3, 3, ‘Padding’, ‘same’) % Output convolutional layer with 3 channels (RGB)
regressionLayer % Regression layer
];
% Define training options
options = trainingOptions(‘adam’, … % Adam optimizer
‘MaxEpochs’, 50, … % Increase the number of epochs
‘MiniBatchSize’, 16, … % Decrease the mini-batch size
‘InitialLearnRate’, 1e-4, … % Decrease the initial learning rate
‘Plots’, ‘training-progress’); % Plot training progress
% Train the network
net = trainNetwork(inputData, targetData, layers, options);
% Denoise the image using the trained CNN
denoisedImage = predict(net, inputData);
% Display the original noisy image and the denoised image
figure;
subplot(1, 2, 1);
imshow(inputData);
title(‘Noisy Image’);
subplot(1, 2, 2);
imshow(denoisedImage);
title(‘Denoised Image’);clc
clear all
close all
image_org=imread(‘C:UserspcOneDriveDesktopmemoirechapitre 3image for test’,’JPG’);
% Gaussian white noise
X = double(image_org) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.01);%NG=gaussian noise
figure(1);subplot(231); imshow(image_org);title (‘image org’)
subplot(233); imshow(NG) ; title (‘Gaussian additive noise’)
NG_gray = rgb2gray(NG);
%averaging filter
f_m = fspecial (‘average’, 3)%f_m=averaging filter
NGmoy = imfilter (NG, f_m,’replicate’);
%gaussian filter
f_g = fspecial (‘gaussian’,3,0.8)%f_g=gaussian filter
NGg = imfilter(NG,f_g,’replicate’);
%median filter
NGmed = medfilt2( NG_gray ,[3 3]);
%the show
subplot(234); imshow(NGmoy);title(‘ avraging Filter ‘)
subplot(235); imshow(NGg);title(‘ gaussien Filtre ‘)
subplot(236); imshow(NGmed);title(‘ median Filtre’)
%PSNR
EQMb=mean2((X-NG).^2 );PSNRb=-10*log10(EQMb);
EQMmoy=mean2( (NG-NGmoy).^2 );PSNRmoy=-10*log10(EQMmoy);
EQMg=mean2( (NG-NGg).^2 );PSNRg=-10*log10(EQMg);
EQMmed=mean2( (NG_gray-NGmed).^2 );PSNRmed=-10*log10(EQMmed);
% Resize the original image to match the input size of the CNN
image_resized = imresize(image_org, [299 450]);
% Add Gaussian noise to the original image
X = double(image_resized) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.03); % Add Gaussian noise
% Display the original and noisy images
figure(1);
subplot(1, 2, 1);
imshow(image_resized);
title(‘Original Image’);
subplot(1, 2, 2);
imshow(NG);
title(‘Noisy Image’);
% Prepare data for training (noisy images as input, original images as target)
inputData = NG; % Noisy images
targetData = X; % Original clean images
% Define the CNN architecture for image denoising
layers = [
imageInputLayer([299 450 3]) % Input layer with the size of the input images
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Convolutional layer with 64 filters of size 3×3
reluLayer % ReLU activation layer
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Another convolutional layer
reluLayer % ReLU activation layer
convolution2dLayer(3, 3, ‘Padding’, ‘same’) % Output convolutional layer with 3 channels (RGB)
regressionLayer % Regression layer
];
% Define training options
options = trainingOptions(‘adam’, … % Adam optimizer
‘MaxEpochs’, 50, … % Increase the number of epochs
‘MiniBatchSize’, 16, … % Decrease the mini-batch size
‘InitialLearnRate’, 1e-4, … % Decrease the initial learning rate
‘Plots’, ‘training-progress’); % Plot training progress
% Train the network
net = trainNetwork(inputData, targetData, layers, options);
% Denoise the image using the trained CNN
denoisedImage = predict(net, inputData);
% Display the original noisy image and the denoised image
figure;
subplot(1, 2, 1);
imshow(inputData);
title(‘Noisy Image’);
subplot(1, 2, 2);
imshow(denoisedImage);
title(‘Denoised Image’); clc
clear all
close all
image_org=imread(‘C:UserspcOneDriveDesktopmemoirechapitre 3image for test’,’JPG’);
% Gaussian white noise
X = double(image_org) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.01);%NG=gaussian noise
figure(1);subplot(231); imshow(image_org);title (‘image org’)
subplot(233); imshow(NG) ; title (‘Gaussian additive noise’)
NG_gray = rgb2gray(NG);
%averaging filter
f_m = fspecial (‘average’, 3)%f_m=averaging filter
NGmoy = imfilter (NG, f_m,’replicate’);
%gaussian filter
f_g = fspecial (‘gaussian’,3,0.8)%f_g=gaussian filter
NGg = imfilter(NG,f_g,’replicate’);
%median filter
NGmed = medfilt2( NG_gray ,[3 3]);
%the show
subplot(234); imshow(NGmoy);title(‘ avraging Filter ‘)
subplot(235); imshow(NGg);title(‘ gaussien Filtre ‘)
subplot(236); imshow(NGmed);title(‘ median Filtre’)
%PSNR
EQMb=mean2((X-NG).^2 );PSNRb=-10*log10(EQMb);
EQMmoy=mean2( (NG-NGmoy).^2 );PSNRmoy=-10*log10(EQMmoy);
EQMg=mean2( (NG-NGg).^2 );PSNRg=-10*log10(EQMg);
EQMmed=mean2( (NG_gray-NGmed).^2 );PSNRmed=-10*log10(EQMmed);
% Resize the original image to match the input size of the CNN
image_resized = imresize(image_org, [299 450]);
% Add Gaussian noise to the original image
X = double(image_resized) / 255;
NG = imnoise(X, ‘gaussian’, 0, 0.03); % Add Gaussian noise
% Display the original and noisy images
figure(1);
subplot(1, 2, 1);
imshow(image_resized);
title(‘Original Image’);
subplot(1, 2, 2);
imshow(NG);
title(‘Noisy Image’);
% Prepare data for training (noisy images as input, original images as target)
inputData = NG; % Noisy images
targetData = X; % Original clean images
% Define the CNN architecture for image denoising
layers = [
imageInputLayer([299 450 3]) % Input layer with the size of the input images
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Convolutional layer with 64 filters of size 3×3
reluLayer % ReLU activation layer
convolution2dLayer(3, 64, ‘Padding’, ‘same’) % Another convolutional layer
reluLayer % ReLU activation layer
convolution2dLayer(3, 3, ‘Padding’, ‘same’) % Output convolutional layer with 3 channels (RGB)
regressionLayer % Regression layer
];
% Define training options
options = trainingOptions(‘adam’, … % Adam optimizer
‘MaxEpochs’, 50, … % Increase the number of epochs
‘MiniBatchSize’, 16, … % Decrease the mini-batch size
‘InitialLearnRate’, 1e-4, … % Decrease the initial learning rate
‘Plots’, ‘training-progress’); % Plot training progress
% Train the network
net = trainNetwork(inputData, targetData, layers, options);
% Denoise the image using the trained CNN
denoisedImage = predict(net, inputData);
% Display the original noisy image and the denoised image
figure;
subplot(1, 2, 1);
imshow(inputData);
title(‘Noisy Image’);
subplot(1, 2, 2);
imshow(denoisedImage);
title(‘Denoised Image’); deep learning, neural network MATLAB Answers — New Questions
Combining text with non-zero elements of a 2D array
I have a numerical array that is "almost" diagonal, so it looks like this:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
I also have a cell array with the same number of rows, which looks like this:
C={‘ABC’;’DEF’;’GHI’;’JKL’;’MNO’}
I would like to create a row array that takes the non-zero values of N, and combines them with the text in C to give an output like this:
CN={‘ABC10_GHI10’ ‘DEF20’ ‘GHI10’ ‘JKL10’ ‘MNO30’}
In other words, it must combine all the non-zero values of each column with text of respective indices.I have a numerical array that is "almost" diagonal, so it looks like this:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
I also have a cell array with the same number of rows, which looks like this:
C={‘ABC’;’DEF’;’GHI’;’JKL’;’MNO’}
I would like to create a row array that takes the non-zero values of N, and combines them with the text in C to give an output like this:
CN={‘ABC10_GHI10’ ‘DEF20’ ‘GHI10’ ‘JKL10’ ‘MNO30’}
In other words, it must combine all the non-zero values of each column with text of respective indices. I have a numerical array that is "almost" diagonal, so it looks like this:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
I also have a cell array with the same number of rows, which looks like this:
C={‘ABC’;’DEF’;’GHI’;’JKL’;’MNO’}
I would like to create a row array that takes the non-zero values of N, and combines them with the text in C to give an output like this:
CN={‘ABC10_GHI10’ ‘DEF20’ ‘GHI10’ ‘JKL10’ ‘MNO30’}
In other words, it must combine all the non-zero values of each column with text of respective indices. cell arrays, combining text and numericals, non-zero element, find MATLAB Answers — New Questions