str2sub

Index numbers for named indices

Syntax

ind = str2sub(x,str)
[ind1,ind2,...,indn] = str2sub(x,str1,str2,...,strn)

Description

example

ind = str2sub(x,str) returns the array ind containing the equivalent index numbers for the optimization variable x corresponding to the named index str. This syntax requires the variable x to have one dimension.

example

[ind1,ind2,...,indn] = str2sub(x,str1,str2,...,strn) returns the n arrays ind1 through indn corresponding to the index number for the optimization variable x corresponding to the named indices str1 through strn. The number of input and output arguments, n, is the number of dimensions of x.

Examples

collapse all

Create an optimization variable that is indexed by names.

colors = {'red','green','blue','white'};
subtractive = ["yellow","cyan","magenta","black","red"];
x = optimvar('x',colors,subtractive);

Find the index numbers for the ('green','magenta') pair.

[ind1,ind2] = str2sub(x,'green','magenta')
ind1 = 2
ind2 = 3

Find the index numbers for all the colors names.

[ind1,ind2] = str2sub(x,colors,repmat("yellow",size(colors)))
ind1 = 

     1     2     3     4

ind2 = 

     1     1     1     1

Find the index numbers for the ('red','red') pair.

[ind1,ind2] = str2sub(x,'red','red')
ind1 = 1
ind2 = 5

Input Arguments

collapse all

Optimization variable, specified as an OptimizationVariable object.

Example: x = optimvar('x',["first","second","third"])

Named index, specified as a string array or as a cell array of character vectors. The number of str arguments must match the number of dimensions of x. The sizes of all the str arguments must be the same.

Example: 'colors'

Data Types: char | string | cell

Output Arguments

collapse all

Index numbers, returned as a vector of positive integers.

For one-dimensional x, ind has the same size as str. For each relevant k,

x(ind(k)) = x(str(k))

For multidimensional x, each ind output has the same size, which is the size of the corresponding input str argument. For each relevant k1,…,kn,

x(ind1(k1),...,indn(kn)) = x(str1(k1),...,strn(kn))

Introduced in R2017b

Was this topic helpful?