How to access a specific element of an Array by using strings?

8 Ansichten (letzte 30 Tage)
Propably there already is an answer to my question, but I don't know how to search for my problem.
Let me explain:
Let's suggest I have the Array A = [9, 7, 5, 1, 3, 8, 2, 6, 4]
and I have a string called str1. This string is changing in a loop. Lets suggest in first step str1 = "id1", in second step str1 = "id2" and in last step str1 = "id3". Each of these id's is an variable, for example id1=3, id2=6, id3=4.
Is there any opportunity to access on an specific element of my Array A by using my string?
For example something like A("str1") or A('str1'), which should be in my first loop step A(id1)=A(3)=5, in my second loop step A(id2)=A(6)=8 and in the last step A(id3)=A(4)=1. None of the opportunities I tried worked for me, there are different error types, for example
"Index exceeds the number of array elements (6)." for A('str1)
or
"Unable to use a value of type string as an index." for A("str1").
It has to be an element-access by a string, because I laod my data from different files all into one script.

Akzeptierte Antwort

Johannes Moor
Johannes Moor am 23 Mär. 2021
I already found a solution by myself. If someone's interested:
A(eval(str1)) does the right thing.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by