0

I create a string like so:

>> str = num2str(123)
str = 
    '123'

str is a 1x3 matrix and so I can for example access the 2 by doing

str(2)
ans = 
    '2'

I was wondering if I can skip creating the variable str and simply access an element of the num2str operation. I tried doing num2str(123)(2):

`num2str(123)(2)`

Error: ()-indexing must appear last in an index expression.

So what, if any, solution is there to accessing an element of a matrix at time of creation?

My actual problem for any who are curious: Upstream from my work area someone has decided to use the index of a 1xn matrix as the identifier for the some data, these identifiers are composed of a sensor identification number and an object identification number, separated by a zero. For example identifier 104 means sensor 1's data on object 4. This also means that elements at indices 1-103 are potentially empty. In my work area I need to do analysis on the sensor data, and I would like to extract the sensor and object numbers programmatically. The quickest way I imagined would be to convert the data indices to strings and then extract the numbers from the strings.

I know I can succeed in doing this just by saving the string to a temporary variable, this is more of a curiosity to me to better understand MATLAB, and I did not see an identical problem... or at least failed to google with the right search terms.

codeNoob
  • 15
  • 3
  • There's a pretty exact dupe already on Stack Overflow. Bottom line: even though it's possible, using a temporary variable and cleaning that afterwards is almost identical in computational load, speed and RAM usage, and a lot cleaner to read. – Adriaan Mar 31 '20 at 15:31
  • As to your actual problem: don't go via strings when it's not necessary. That's just slow. If you have an (almost) empty matrix, take a peek at [`sparse()`](https://mathworks.com/help/matlab/ref/sparse.html). You can then use a `[row,col,val] = find()` on the whole sparse matrix to find indices + the desired value. Another option is to use [`nzz()`](https://athworks.com/help/matlab/ref/nzz.html) to get a logical mask of non-zero values, and use `ind2sub` to get row/column values. – Adriaan Mar 31 '20 at 15:33
  • 1
    Or, just use math. `mod(idivide(123, 10), 10)`. – beaker Mar 31 '20 at 16:08

0 Answers0