Filter löschen
Filter löschen

Looping through cell array in order

1 Ansicht (letzte 30 Tage)
Josh
Josh am 10 Dez. 2014
Kommentiert: Josh am 11 Dez. 2014
I'm drawing squares on a grid. The squares need to have an ID as set within a cell array. I was expecting the ID to loop through each ID in the cell in order by instead it cycles through in rows.
&nbsp
cell_id = cell(1, 2); % 1 x 5 cell array
cell_id{1, 1} = 1365;
cell_id{1, 2} = 1256;
cell_id{1, 3} = 6214;
cell_id{1, 4} = 2587;
cell_id{1, 5} = 1564;
hold on
for i = 1:2:12
count = 1;
for ii = 1:2:12
plot(1*i , 1*ii, 's', 'MarkerSize', 50);
if (count <= 5)
id = cell_id(1,count);
text(1*i, 1*ii, ['ID:',id]);
count = count + 1;
elseif (count > 5)
id = cell_id(1,1);
count = 1;
text(1*i, 1*ii, ['ID:',id]);
end
end
end
Any ideas, thanks.
  1 Kommentar
per isakson
per isakson am 10 Dez. 2014
Bearbeitet: per isakson am 10 Dez. 2014
  • Do you expect 4 rows times 6 columns of boxes?
  • Replace i by xx and ii by yy or something associated with directions
  • Set the axes limits before adding the boxes. It's confusing that the limits change all the time
  • And format the code properly. (I did it this time.)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume
Guillaume am 10 Dez. 2014
You appear to be a bit confused about a few things:
cell_id = cell(1, 2);
declares a 1 x 2 cell array, not a 1 x 5. Anyway, you could replace your first two lines with:
cell_id = {1365, 1256, 6214, 2587, 1564};
Secondly, you reset your count for each column, since it's set to one in the first for loop. You probably meant to do the assignment to 1 before the first loop.
Also, use more descriptive variables than i and ii. row and col would be better.
To sum it up:
figure; axis off; hold on;
cell_id = {1365, 1256, 6214, 2587, 1564};
count = 1;
for col = 1:2:12
for row = 1:2:12
plot(col, row, 's', 'MarkerSize', 50);
text(col, row, sprintf('ID:%d', cell_id{count}));
count = mod(count, numel(cell_id)) + 1;
end
end
  7 Kommentare
Image Analyst
Image Analyst am 11 Dez. 2014
I see no reason for a cell array at all. What about this requires cells instead of a simple numerical array?
Josh
Josh am 11 Dez. 2014
Oops, perfect thanks. Good explanation

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Graphics Performance finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by