フィルターのクリア

Hi, I'm new to Matlab. I keep getting Index exceeds matrix dimensions error. Maybe someone can help me with this.

3 ビュー (過去 30 日間)
function [ J ] = J_springs( x )
%Jacobian Matrix Jf
%df/dx(i) df/dx(i-1) df/dx(i+1)
%Initialization
x=1:20
N=20
K=zeros(N,1);
b=zeros(N,1);
J=zeros(N,1);
for i = 1:N
K(i) = (100+i-N/2); %N/cm
b(i) = (-10+0.1*(i-N/2)); %N/cm^3
end
for i = 2:N-2
J(i,i) = -(K(i,i)+K(i+1,i))+3*b(i,i)*(x(i,i)-x(i-1,i))^2+3*b(i+1,i)*(x(i+1,i)-x(i,i))^2;
end
%
for i = 2:N-1
J(i,i-1) = K(i,i-1)-3*b(i,i-1)*(x(i,i-1)-x(i-1,i-1))^2;
end
%
for i = 1:N-2
J(i,i+1) = K(i+1,i+1)-3*b(i+1,i+1)*(x(i+1,i+1)-x(i,i+1))^2;
end
%
end

採用された回答

Walter Roberson
Walter Roberson 2017 年 12 月 13 日
K=zeros(N,1);
So K is a column vector with N rows.
for i = 1:N
K(i) = (100+i-N/2); %N/cm
b(i) = (-10+0.1*(i-N/2)); %N/cm^3
end
so the first N entries in K are initialized (that is, all of it.)
for i = 2:N-2
J(i,i) = -(K(i,i)+K(i+1,i))+3*b(i,i)*(x(i,i)-x(i-1,i))^2+3*b(i+1,i)*(x(i+1,i)-x(i,i))^2;
end
So i starts from 2, so the right hand side immediate starts trying to evaluate K(i,i) which is K(2,2) but K only has one column.
  3 件のコメント
Walter Roberson
Walter Roberson 2017 年 12 月 13 日
Most of your code does not make sense unless you are using 2D arrays instead of column vectors. However, I would then expect you to be doing nested loops instead of single loops.
If I were writing the code, I would vectorize. For example instead of
for i = 2:N-2
J(i,i) = -(K(i,i)+K(i+1,i))+3*b(i,i)*(x(i,i)-x(i-1,i))^2+3*b(i+1,i)*(x(i+1,i)-x(i,i))^2;
end
I would look at
J(2:N-1, 2:N-1) = -K(2:N-1,2:N-1)+K(3:N,2:N-1)) + 3 * b(2:N-1,2:N-1) * (x(2:N-1, 2:N-1) - X(1:N-2, 2:N-1)).^2 + 3 * b(3:N, 2:N-1) * (x(3:N, 2:N-1) - x(2:N-1, 2:N-1)).^2;
Muhamad Mohd-Adly
Muhamad Mohd-Adly 2017 年 12 月 14 日
Sir,
thank you very much. It work now. Much appreciated!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by