Clear Filters
Clear Filters

array access

1 view (last 30 days)
mohamed saber
mohamed saber on 25 Nov 2011
n=0;
while abs(dQ)>.000001 % tolerance
n=n+1;
if dQ>.000001 % dQ is positive ... Ej must be increased
Ej=1.0001*Ej; % increase in Ej
elseif dQ< .000001 % dQ is negative ... Ej must be decreased
Ej=.999*Ej; % decreased in Ej
end
Ej(n)=Ej; % array of Ej
% new Q calculatio
Q1=((abs(E1-Ej))./(R1)).^.5;
Q2=((abs(E2-Ej))./(R2)).^.5;
Q3=((abs(E3-Ej))./(R3)).^.5;
% new dQ calculation after increase or decrease Ej
if Ej>E2
dQ=Q1-Q2-Q3;
elseif Ej<E2
dQ=Q1+Q2-Q3;
end
end % end of while loop
the error is
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
Error in ==> try4 at 75
Ej(n)=Ej; % array of Ej
why ???????????????????????????????

Answers (1)

Walter Roberson
Walter Roberson on 25 Nov 2011
The first time through the loop you show, Ej is not defined at at all, so the code would fail.
If you had predefined Ej as a scalar variable such as
Ej = 1.43e-7
then in MATLAB a scalar is the same thing as a vector with one argument, so in this case Ej and Ej(1) would be the same thing, and when n is 1, Ej(n) would be Ej(1) and assigning Ej(n) = Ej would be Ej(1) = Ej(1) so that would work.
Then the second time through the loop, when n = 2, Ej would still be a scalar, until you got to the statement Ej(n) = Ej . With n = 2 and Ej being a scalar (and thus being the same as Ej(1)) you would be making the assignment Ej(2) = Ej(1) which would result in Ej now becoming a vector with two elements, with Ej(1) and Ej(2) being individual scalar values, and Ej with no subscript referring to the entire vector, [Ej(1),Ej(2)] .
Then the third time through the loop, when n=3, the calculations made with Ej are vector calculations that return a vector of two values, because Ej without a subscript refers to the entire vector. Then with n=3 you get to Ej(n)=Ej which would be Ej(3) = Ej which would be Ej(3) = [Ej(1),Ej(2)] ... and there you are, trying to store the two values of the right-hand-side in to the single location named on the left hand side. You cannot put two values in to one location, so MATLAB errors out with the error message you saw.
I do not know what the intention of your code is, so I cannot advise you on what you need to do to fix it.

Tags

Community Treasure Hunt

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

Start Hunting!