Effacer les filtres
Effacer les filtres

how to delete any variable from outside the for loop

1 vue (au cours des 30 derniers jours)
singh
singh le 26 Avr 2015
Réponse apportée : dpb le 26 Avr 2015
N=20;
area=100;
X=rand(1,N)*area;
Y=rand(1,N)*area;
htext=[];
for i1=1:2
for i=1:N
htext(i)=text(X(i),Y(i),num2str(i),'fontsize',20);
hold on
end
end
for ii=1:5
delete(htext(ii));
end
now error is come when delete(htext) is execute plz give me some solution.
beacuse it show the message when cursor move on the htext variable 'htext size will be change every iteration '.how to delete hetxt value in for loop and out of for loop.

Réponses (1)

dpb
dpb le 26 Avr 2015
The warning "htext size will be change every iteration" is from having not preallocated the array so it "grows" automagically every iteration. Use preallocation as the warning suggests to make that go away. Instead of
htext=[];
htext=zeros(N,1);
would preallocate the array to zeros.
Your code that causes the actual error, however is owing to the line you executed in the command window but didn't put into the code snippet...
delete(htext)
by itself already deleted the whole array of N handles to the text objects so the loop has none left that haven't been deleted to operate over. Remove that loop it's superfluous (that is, uneeded).
However, you have some other problems here -- you have the plot and text function loop inside another loop for 1:2 for some reason so you're actually creating 2*N line and text handles, not just N. But, since your index saving the text handles is only from 1:N, the second time through that loop you write over the same five locations and thus have lost "oprphaned" the first five handles and no longer have access to them. The way to solve this would be to move the lines
delete(htext)
pause(0.9)
to just before the end of the inner loop (and again, delete the other loop entirely).
Another comment on Matlab in general; you don't need the loop at all, anyway, plot and text are vectorized -- you can simply write
hplot=plot(X,Y);
htext=text(X,Y,num2str([1:N].'),'fontsize',20);
NB: the .' on the 1:N vector; num2str needs a column vector to operate correctly to place the array elements on subsequent rows; otherwise they'll get strung together in one long row instead. Also, plot uses the columns of X,Y arrays as individual lines; generate them as column vectors, not row vectors as you have here (or transpose them in the call but it's simpler to just create them as going to use them in the first place).

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by