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!