Matlab編程實例(3) 函數向左或向右平移N點 左移右移


 

%函數移動
close all;
clear all;
dir=input('請輸入平移方向,“1”為向左,“2”為向右');
if dir~=1&&dir~=2;%輸入控制
   error('您的輸入有誤!');
end;
step=input('請輸入平移步數');
Samp=200;  %設置信號的采樣精度
A=10;%信號幅值
na=1;%噪聲放大系數
w=1;
p=0;
t = linspace(0,6*pi/w,Samp); %創建函數向量
f=A*sin(w*t+p)+na*randn(1,Samp);%構造一個標准函數
%函數平移
y=rotate(f,dir,step);
plot(t,f,'b');
hold on;
plot(t,y,'r');
 
 
///////rotate.m/////////
function y=rotate(f,dir,step);
%函數平移 f為目標函數 dir為平移方向 向左為1 向右為2 step為平移步數
len=length(f);%取得f長度
%當向左平移時
if dir == 1 ;
 for n=0:1:step;
  temp=f(len);%將最后一個元素取出保護
   for  m=1:1:len-1%所有點向后移動一位
   f(len-m+1)=f(len-m); 
   f(1)=temp;%將最后一點放入第一點
 end
end
end
%當向右平移時
if dir == 2 ;
 for n=0:1:step;
  temp=f(1);%將最后一個元素取出保護
   for  m=2:1:len%所有點向后移動一位
   f(m-1)=f(m); 
   f(len)=temp;%將最后一點放入第一點
 end
end
end
y=f;%代回
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM