How to use for loop for my code? (clean code)
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Walter Roberson
2023-4-28
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.
回答(1 个)
Swapnil Tatiya
2023-6-19
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:
%%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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 ECG / EKG 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!