# automatic variable creation?

5 views (last 30 days)
Marcin Zyskowski on 23 Oct 2016
Commented: Walter Roberson on 23 Oct 2016
I want my program to scan the array of mixed 0's and 1's and create a new variable every time it encounters a zero. I want these variables to last long and contain coordinates of respective zeros. For example, for array:
1 0 1 1 0
0 1 1 1 1
1 1 0 0 1
I would like to have automatically generated variables:
var_1 = [1,2]
var_2 = [1,5]
var_3 = [2,1]
var_4 = [3,3]
var_5 = [3,4]
How to do that? Presented problem is just a part of much bigger problem and I need few variables to deal with the rest of problem.
Walter Roberson on 23 Oct 2016

Chaya N on 23 Oct 2016
It would be more efficient to simply store all these indices inside one variable (or array/ cell array/ structure, as the case may be). You could look up the find function or Matrix Indexing for more information.

Image Analyst on 23 Oct 2016
Try this:
[rows, columns] = find(yourArray == 0);
rows and columns are synced up, so like you wanted the 4th zero in the array, it would happen at rows(4) and columns(4). If you want a single (row, col) array instead of two separate ones, simply stitch them together:
rc = [rows, columns]; % Each row is row, column
or if you want (x,y) instead of (row, column), just reverse them:
xy = [columns, rows];
Chaya N on 23 Oct 2016
Marcin, I am going to go out on a limb here and guess that your original question about creating separate variables was due to the ease of being able to see which pair of co-ordinates you were using(?)
If so, please use the method shown above here. I will also add here (again) that knowing how the find function works would make your understanding easier. As an illustration with your example:
x = [1 0 1 1 0 % your example here
0 1 1 1 1
1 1 0 0 1];
[rows, columns] = find(x == 0); % From answer above
rc = [rows, columns]; % Also from answer above
gives
rc =
2 1
1 2
3 3
3 4
1 5
These are the exact pairs of indices that you have in your (multiple) variables above, but note the order in which they appear here.
The find function processes the data in an array in a very particular order namely, top to bottom (column-wise) and then left to right (row-wise).
Once you have these indices, you would access them as an array too! For example, rc(2,:) gives you [1,2], which is the second pair of indices in rc and corresponds to the zero on the first row at the second column.