Number of elements error

조회 수: 1 (최근 30일)
Mohammad Ezzad Hamdan
Mohammad Ezzad Hamdan 2019년 3월 18일
댓글: Matt J 2019년 3월 18일
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
Mohammad Ezzad Hamdan 2019년 3월 18일
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
Mohammad Ezzad Hamdan 2019년 3월 18일
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