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

8 vues (au cours des 30 derniers jours)
Johannes Moor
Johannes Moor le 23 Mar 2021
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.

Réponse acceptée

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

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by