Matlab: Inconsistency in numbering pattern of legend entries

141 Views Asked by At

I am plotting multiple lines inside a loop using hold(Ax, 'on'). To manage the legend updating each time a new line is added, I am appending my legends as:

reshape(sprintf('Zone #%02d',1:ii), 8, ii)'

Where ii is the loop iteration counter. This produces the legend entries as Zone #01, Zone #02, Zone #03 etc.
Now, instead of above entries, I want to produce the legend entries as Zone # 1 and 2 Intersection, Zone # 2 and 3 Intersection, Zone # 3 and 4 Intersection etc. To get this pattern I did something like reshape(sprintf('Zone # %01d and %01d Intersection', 1:ii, 2:ii + 1), 27, ii), but it messes up the consistency in numbering pattern if ii is greater than 3 as shown below:

enter image description here

Can you spot where am I going wrong? Thanks as always!

1

There are 1 best solutions below

0
On BEST ANSWER

Yes - the way Matlab interprets your statement, it will first "consume" the entire first array, then the second. So if you say

sprintf('%d %d ', 1:5, 2:6)

the output will be

1 2 3 4 5 2 3 4 5 6

It just so happens that you are getting it "almost right" for a little bit because of the way you were trying to do things and that became confusing.

The correct way to achieve what you want is make sure that the order in which variables are consumed by matlab is the order you need. An example of doing this would be

sprintf('%d %d ', [1:3; 2:4])

When matlab accesses the array you created

1 2 3
2 3 4

It does so by going down the colums - so it sees

1 2 2 3 3 4

To generate the legend you want, use

reshape(sprintf('Zone # %01d and %01d Intersection', [1:ii; 2:ii + 1]), 27, ii)'

Which results in

Zone # 1 and 2 Intersection
Zone # 2 and 3 Intersection
Zone # 3 and 4 Intersection
Zone # 4 and 5 Intersection
Zone # 5 and 6 Intersection

for ii = 5 . Note I transposed the output of the reshape to achieve this (that's the ' at the end of the line)