for loop not working

1 view (last 30 days)
C.G.
C.G. on 27 May 2020
Commented: Rik on 3 Jun 2020
I have 2 frames of a video containing 700 balls.
I want to create a series of subimages, defined by the coordinates of the balls, so I have 700 individual ball images.
The code below generates 1 ball image, but I cannot get it to loop through the rest of the 699 ball coordinates.
Can anybody help me adapt this loop?
r = 20; %radius of whole ball
for k = 1:numFrames
%subimage the balls in frames 1 and 2 by shrinking them to the coordinates of the balls
%should produce a series of images (700 ish) showing each individual
%ball
subframe1 = frame_1(round(yb_1{k})-r:round(yb_1{k})+r, round(xb_1{k})-r:round(xb_1{k})+r); %Issue - not getting all balls
%check its worked
figure(4)
imshow(subframe1)
end
  4 Comments
C.G.
C.G. on 29 May 2020
Somebody else wrote the first half of the code with the ball coordinates as yb_1 etc, and now im using that to do this next step

Sign in to comment.

Answers (1)

Rik
Rik on 29 May 2020
Then you are stuck with first undoing that mistake. You should convert those coordinate variables to a single array. You can use two strategies:
  1. Save the workspace that contains all those numbered variables (with the save function), then use load to load to a struct. Now you can use S.(sprintf('yb_%d',ball_index)) to retrieve the values and store it in the array.
  2. Use eval to evaluate that char. Use it only once to fix this mistake. If you can fix the source that would be even better.
Now you have an array with the ball coordinates, so it is trivial to write an inner loop that loops over all the balls.
Why are numbered variables like this so bad? (I have taken the liberty of adapting some of Stephen Cobeldick's thoughts on this topic) Introspective programing (e.g. eval, assignin and other functions like it) is slow, and the MATLAB documentation warns specifically against it. Using eval is slow, makes debugging difficult, and removes all code helper tools (code checking, syntax hints, code completion, variable highlighting, etc.). A longer discussion can be found here. If you are not an expert and you think you need eval, there are probably better solutions to your problem. Also, if you are not an expert, you might find interesting and helpful hints on this page (and if you are an expert, you can still learn from it).
  8 Comments
Rik
Rik on 3 Jun 2020
How would you like them to be ordered? You can use montage, but then you have to make sure all subimages are in the same 4D array:
%before your loop:
montage_data=zeros(2*r+1,2*r+1,1,numballs);%row,col,color_channel,balls
%in your loop:
montage_data(:,:,:,i)=subframe1;

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!