How to use for loop for my code? (clean code)
1 view (last 30 days)
Show older comments
1) I would like to clean my code, using for loop (or everything else like if ).
2) Is it correct how I Added Noise to my Signal?
this is my code.
clc
clear all
close all
%% Loading Data
cd 'F:\1401_phd\term 2' %change file path
ecg =load ('Ecg.txt');
%% 300 points of ecg
sig=ecg(1:300);
%% Adding noise
no1=mvnrnd(0,2,300);
no2=mvnrnd(0,2,300);
no3=mvnrnd(0,2,300);
no4=mvnrnd(0,2,300);
no5=mvnrnd(0,2,300);
no6=mvnrnd(0,2,300);
no7=mvnrnd(0,2,300);
no8=mvnrnd(0,2,300);
no9=mvnrnd(0,2,300);
no10=mvnrnd(0,2,300);
sig1=sig+no1;
sig2=sig+no2;
sig3=sig+no3;
sig4=sig+no4;
sig5=sig+no5;
sig6=sig+no6;
sig7=sig+no7;
sig8=sig+no8;
sig9=sig+no9;
sig10=sig+no10;
%% Averaging
avr=(sig1+sig2+sig3+sig4+sig5+sig6+sig7+sig8+sig9+sig10)/10
figure
subplot(4,1,1)
plot(sig1)
subplot(4,1,2)
plot(sig2)
subplot(4,1,3)
plot(sig3)
subplot(4,1,4)
plot(avr)
1 Comment
Walter Roberson
on 28 Apr 2023
Please read http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval for information about why we strongly recommend against creating variable names dynamically.
Answers (1)
Swapnil Tatiya
on 19 Jun 2023
To have a cleaner code, you can make use of matlab matrices as follows:
%As you're creating 10 noise variables,it can be just put inside one
%variable and can be used by proper indexing
noise=zeros([10 300]);
for i=1:10
noise(i,:)=mvnrnd(0,2,300);
end
%At the end of this loop you shall have 10 noise arrays indexed as :
%noise(i,:) for i∈{1,2,3.....,9,10}
%and the matrix will look as follows:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1414329/image.png)
%%I'm generating a random signal just to test,you can use the ecg signal
%%that u've used earlier
sig=rand([1 300]);
%I'm naming sig1,sig2....sig10 to noisySignals and making just one variable
%that holds all the signals as follows:
noisySignals=zeros([10 300]);
for i=1:10
noisySignals(i,:)=sig+noise(i,:);
end
%mean() -> inbuilt function that takes average
avg=mean(noisySignals);
This shall be a cleaner way of writing the same code.
And regarding the 2nd part of your question,that is dependent on what kind of noise you want to add as ECG in real life contains a combination of different kinds of noise.
0 Comments
See Also
Categories
Find more on ECG / EKG in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!