Number of elements error
1 回表示 (過去 30 日間)
古いコメントを表示
p = [2 3 4 5 6 7 8 9 10];
L2 = zeros(size(p));
xchange = zeros(size(p));
f = @(x) (cos(2*x)).*(sin(x)-0.5*x.^2);
for j = 1:length(p)
n = 2^(p(j));
x = linspace(-3,3,n);
dx = x(2)-x(1);
L = 0;
ff = [];
for i = 3:(length(x)-2)
ff = (-f(x(i+2))+6*f(x(i+1))-3*f(x(i))-2*f(x(i-1)))/(6*dx);
%ff = (-1*x(i+2)+6*x(i+1)-3*x(i)-2*x(i-1))/(6*dx);
L(i) = dx*((f(x(i))-ff)^2);
L = L + L(i);
end
%ff(1:2) = ff(3);
%ff(n-1:n) = ff(n-2);
L2(j) = L.^0.5;
xchange(j) = dx;
end
plot(log(xchange),log(L2))
hold on
Hi, can anyone help me with this. I have been spending hours to solve the error printed in the command window below;
"Unable to perform assignment because the left and right sides have a different number of
elements.
Error in Untitled2 (line 24)
L2(j) = L.^0.5;"
2 件のコメント
Geoff Hayes
2019 年 3 月 18 日
Mohammad - in the line of code
L2(j) = L.^0.5;
L2 is a 9x9 matrix and L is an array of different lengths (depending upon p). So the above code is trying to assign an array to a scalar element of your L2 matrix. Do you really mean to assign an array here? Should L2 be a cell array so that you can assign differently sized vectors/arrays to it?
採用された回答
Matt J
2019 年 3 月 18 日
編集済み: Matt J
2019 年 3 月 18 日
for i = 3:(length(x)-2)
ff(i) = (-1*x(i+2)+6*x(i+1)-3*x(i)-2*x(i-1))/(6*dx);
L = L + dx*((f(x(i))-ff(i))^2);
end
4 件のコメント
Matt J
2019 年 3 月 18 日
It runs fine for me.
p = [2 3 4 5 6 7 8 9 10];
L2 = zeros(size(p));
xchange = zeros(size(p));
f = @(x) (cos(2*x)).*(sin(x)-0.5*x.^2);
for j = 1:length(p)
n = 2^(p(j));
x = linspace(-3,3,n);
dx = x(2)-x(1);
L = 0;
ff = [];
for i = 3:(length(x)-2)
ff = (-f(x(i+2))+6*f(x(i+1))-3*f(x(i))-2*f(x(i-1)))/(6*dx);
%ff = (-1*x(i+2)+6*x(i+1)-3*x(i)-2*x(i-1))/(6*dx);
L = L + dx*((f(x(i))-ff)^2);
end
%ff(1:2) = ff(3);
%ff(n-1:n) = ff(n-2);
L2(j) = L.^0.5;
xchange(j) = dx;
end
plot(log(xchange),log(L2))

その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Special Functions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!