U=zeros(1,2,'sym');
B=zeros(10,'sym');
U(1)=1;
U(2)=a;
for k=1:10
B(1)=0;
for i=1:k
B(1)=B(1)+U(i)*U(k-i+1)
end
end
It is displaying the error for B(1)=B(1)+U(i)*U(k-i+1)

6 Kommentare

DGM
DGM am 1 Jun. 2021
Bearbeitet: DGM am 1 Jun. 2021
The index expressions i and (k-i+1) both span from 1 to 10. The vector U only has two elements.
You're also resetting B(1) to zero every time through the outer loop, recalculating it repeatedly, overwriting the prior result in the inner loop, ... and then resetting it back to zero again. You'll have to straighten that out.
yogeshwari patel
yogeshwari patel am 1 Jun. 2021
so i need to consider it as B
Rik
Rik am 1 Jun. 2021
What do you want to do? You must have some goal in mind. Your code doesn't contain any comments or descriptive variable names, so that isn't any help either.
U=zeros(1,2,'sym');
B=zeros(10,'sym');
U(1)=1;
U(2)=a;
for k=1:10
B(1)=0;
for i=1:k
B(1)=B(1)+U(i)*U(k-i+1)
end
U(k+1)=U(k)-B(1);
end
I want to calculate all the values of U
DGM
DGM am 2 Jun. 2021
Okay, that's one more bit of info, but that still doesn't clarify much. Why does B have 100 elements if you're only using one? Why does U only have 2 elements if you're trying to use 10 (actually you're now trying to use up to 11). I guess you could do like the answer below and just specify U to have 10 (or 11) elements instead of 2, but you're also assigning U(2) and then overwriting it.
I think what everyone is saying boils down to a common problem in communicating intent in code. The loop structure is incongruous when considering the array sizes. Since the intent and variable meaning are unknown at a conceptual level and the code as presented doesn't do what's desired, there's nothing left to tell us what it's supposed to do.
If offering a potential solution requires too many tenuous assumptions of intent, I don't think I'm alone in hesitating to add more confusion to the discussion by fishing with guesses.
yogeshwari patel
yogeshwari patel am 2 Jun. 2021
Thanks for your comment.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Girijashankar Sahoo
Girijashankar Sahoo am 1 Jun. 2021

0 Stimmen

B(1)=B(1)+U(i)*U(k-i+1)
% Here you defined length(U)=2 while U(i)*U(k-i+1) is over indexed value
% So my suggestion denfine U=zeros(1,10,'sym')

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by