2015-09-22 24 views
0

所以我試圖讓計算傅立葉級數,並繪製它.m文件,但我一直收到錯誤我如何解決「下標指數必須是真正的正面」?

Subscript indices must either be real positive integers or logicals. 

我已經找到了其中的代碼錯誤的位置,但我沒有想法如何解決這個問題,你能幫我理解這個錯誤嗎?

當我嘗試在sum(a0)中總結我的功能時發生錯誤。

我的代碼:

syms k x 

f = [... 
    cos(x) 
    ]; 

a = [... % Hele perioden 
    -pi pi; 
    ]; 



sum = [2 5 20]; % N - Antal af Fourie-skridt. 

%% Fourie Koeffiecienter 
for i = 1:length(f) 
    a0(i) = int(f(i),x,a(i,:)); %a_0 findes 
    ak(i) = int(f(i)*cos(k*pi*x/max(a(:))),x,a(i,:)) ; %a_k findes 
    bk(i) = int(f(i)*sin(k*pi*x/max(a(:))),x,a(i,:)) ; %b_k findes 
end 

a0 = 1/(2*max(a(:))) * sum(a0); 
ak = 1/(max(a(:))) * sum(ak); 
bk = 1/(max(a(:))) * sum(bk); 


%% Summen for 3 forskellige N 
x = linspace(a(1,1),max(a(:)),25); %linspace til x for hele perioden. 


fsum_1 = a0 + symsum(ak*cos(k*pi*x/max(a(:))) + bk*sin(k*pi*x/max(a(:))),k,1,sum(1,1)); 
fsum_2 = a0 + symsum(ak*cos(k*pi*x/max(a(:))) + bk*sin(k*pi*x/max(a(:))),k,1,sum(1,2)); 
fsum_3 = a0 + symsum(ak*cos(k*pi*x/max(a(:))) + bk*sin(k*pi*x/max(a(:))),k,1,sum(1,3));%F.R sum 


%% plot 
subplot(3,1,1) 
plot(x,fsum_1) 
title(['Fourierække ved n =',num2str(sum(1,1))]) 

subplot(3,1,2) 
plot(x,fsum_2) 
title(['Fourierække ved n =',num2str(sum(1,2))]) 

subplot(3,1,3) 
plot(x,fsum_3) 
title(['Fourierække ved n =',num2str(sum(1,3))]) 

回答

4

你的問題是,你已經使用sum作爲變量。通過這樣做,你可以超載內建函數sum()。因此,當您嘗試執行:sum(a0)時,MATLAB嘗試使用a0作爲明顯失敗的矢量sum的索引。你可能workaround this,但我不會推薦它,因爲很容易忘記你從現在起在一週/一個月/一年內使用代碼時做到了這一點。

MATLAB有很多內建函數,其中大多數都有非常直觀的名稱。 sum, max, min, length, size, abs, ...the list goes on。儘量避免使用變量名稱這樣的名稱,因爲這可能會輕易搞亂你的代碼。看看this question,我想你會發現它很有趣。

此外,使用i and j as variable names in MATLAB is not recommended(儘管你可能在MATLAB 101中學到了它)。

關於編程的好處是,你很少第一個擁有encountered the problem。有147個問題與SO上發佈完全相同的錯誤消息。你可以看看丹尼斯generic solution,或者任何的the​​e(< =字母是鏈接。)

+0

很好的回答。 MATLAB真的不應該允許覆蓋內置函數,這將節省大約147個問題:) – Adriaan

+0

Thanks @Adriaan!我敢打賭這比147多得多!並非所有人都設法在錯誤信息中提出問題。而且,我其實不同意你的看法。在Mathworks決定創建一些函數的時候,你會突然產生許多毫無價值的代碼。 'my_sum','abs_val','res','results' +++。編輯器中的警告將會很好,儘管=) –

+0

嗯,他們可以禁止它,並顯示與當前「將在未來版本中刪除」的函數相同的警告。無論如何,警告會很好。 – Adriaan

相關問題