Assigning vectors to a list of names

8 vues (au cours des 30 derniers jours)
Davide
Davide le 15 Déc 2024
Hello everyone, I have a list of str values and to every name I want to associate a vector of two elements, but I can't do it directly.
just as an example, i want to assign the vector [1,2] to each element of the list:
vectors=['name1','name2','name3','name4','name5']
for i=1:length(vectors)
vectors(i)=[1,2]
end
but as long as vectors(i) is a str value i can't do it. Pls help me with this, I know it's very simple but I'm stuck on it.
  2 commentaires
Stephen23
Stephen23 le 15 Déc 2024
John D'Errico
John D'Errico le 15 Déc 2024
Learn to use arrays. Cell arrays. Structs. All sorts of things that CAN be used far more effectively than what you incorrectly think you want to do.

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 15 Déc 2024
Modifié(e) : Voss le 15 Déc 2024
vectors = "name"+(1:5)
vectors = 1x5 string array
"name1" "name2" "name3" "name4" "name5"
Given that string array of names, rather than creating a variable for each name, you can create a scalar struct with a field for each name, with each field's value being the vector [1,2].
Here's one way to do that:
C = cellstr(vectors);
C(2,:) = {[1,2]};
S = struct(C{:})
S = struct with fields:
name1: [1 2] name2: [1 2] name3: [1 2] name4: [1 2] name5: [1 2]
Then in the rest of your code, when you want to refer to the vector for name "name1", you can write
S.name1
ans = 1×2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
and so on.
For example you can assign a new value to the 'name3' vector:
S.name3 = [1 2 3]
S = struct with fields:
name1: [1 2] name2: [1 2] name3: [1 2 3] name4: [1 2] name5: [1 2]
If the name is stored in a variable, that's easy to accommodate as well:
vector_name = 'name4';
% retrieval:
S.(vector_name)
ans = 1×2
1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% assignment:
S.(vector_name) = [1 2 3 4]
S = struct with fields:
name1: [1 2] name2: [1 2] name3: [1 2 3] name4: [1 2 3 4] name5: [1 2]

Plus de réponses (1)

Walter Roberson
Walter Roberson le 15 Déc 2024
It isn't hard.
vectors=["name1","name2","name3","name4","name5"];
tname = tempname + ".m";
[fid, msg] = fopen(tname, 'w');
if fid < 0; error('failed to open "%s" because "%s"', tname, msg); end
for K = 1 : length(vectors)
fprintf(fid, '%s = [1 2];\n', vectors(K));
end
fclose(fid);
run(tname);
delete(tname);

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by