why does the window show me x3=27 when x3=1:2:50?

I wrote this code ,and the c3 can be a vector ,the elements in this vector is the result of every loops,however,i found that the window show me an error ,here is my code
XX3=1:2:50
AXX3=zeros(1,length(XX3))
a3=5
b3=-3
for x3=1:2:50
y3=a3*x3^2+b3
c3(x3)=AXX3(x3)+y3
end
And here is the error
Attempted to access AXX3(27); index out of bounds
because numel(AXX3)=25.
Error in wqeqwe (line 7)
c3(x3)=AXX3(x3)+y3
I found that the x3 = 27.i wonder why? x3 is 1:2:50.there should be only 25 elements,i mean ,x3 should be as same as XX3,does anyone know where is my mistake

답변 (1개)

madhan ravi
madhan ravi 2019년 3월 31일
편집: madhan ravi 2019년 3월 31일

0 개 추천

No loop's needed:
XX3=1:2:50;
a3=5;
b3=-3;
x3=1:2:50;
y3=a3*x3.^2+b3;
AXX3=zeros(size(XX3));
c3=AXX3+y3; % if AXX3 is zero then why add it with y3 to get c3?

댓글 수: 5

madhan ravi
madhan ravi 2019년 3월 31일
편집: madhan ravi 2019년 3월 31일
Reason for your error:
AXX3 - has 25 elements but inside the loop you try to access 27th element which is out of bounds.
Your loop would be:
XX3=1:2:50;
AXX3=zeros(size(XX3));
a3=5
b3=-3
x3=1:2:50;
c3=zeros(size(XX3)); % pre-allocate
for k=1:numel(x3);
y3=a3*x3(k)^2+b3;
c3(k)=AXX3(k)+y3;
end
but where is 27 from in my code?the window show me x=x3=1:2:50,and x3=27,it is strange
madhan ravi
madhan ravi 2019년 3월 31일
편집: madhan ravi 2019년 3월 31일
>> x3 = 1:2:50
x3 =
Columns 1 through 13
1 3 5 7 9 11 13 15 17 19 21 23 25
Columns 14 through 25
27 29 31 33 35 37 39 41 43 45 47 49
%^^-------??????????????????
>>
I suggest you to do Matlab onramp course and learn the basics of MATLAB.
When you try to access the 27th element MATLAB stops the execution showing the warning, so the last value of x3 is 27, that being stored in the workspace when x3 is typed in command window you get a scalar 27 since you run it a loop, clear?
ok i understand,but why will the matlab stop and warn when when the x3 is 27?
madhan ravi
madhan ravi 2019년 3월 31일
편집: madhan ravi 2019년 3월 31일
% example
x = 1:25 % 25 elements
x(27) % will throw error why?
% ^^---- there exists no such element in the 27th place in x because x has only 25 elements not 27, get it?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2019년 3월 31일

편집:

2019년 3월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by