Number of elements error

2 次查看(过去 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
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?
Mohammad Ezzad Hamdan
Thank you for your reply,
i have changed the two lines below....
L2 = zeros(1,length(p));
xchange = zeros(1,length(p));
... and yet still getting the same error message.

请先登录,再进行评论。

采纳的回答

Matt J
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 个评论
Mohammad Ezzad Hamdan
still getting error message
Matt J
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))
untitled.png

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by