필터 지우기
필터 지우기

How to use for loop for my code? (clean code)

조회 수: 2 (최근 30일)
mary keshtkar
mary keshtkar 2023년 4월 28일
답변: Swapnil Tatiya 2023년 6월 19일
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개)

Swapnil Tatiya
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.

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by