Assigning vectors to a list of names
10 views (last 30 days)
Show older comments
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 Comments
John D'Errico
on 15 Dec 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.
Accepted Answer
Voss
on 15 Dec 2024
Edited: Voss
on 15 Dec 2024
vectors = "name"+(1:5)
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{:})
Then in the rest of your code, when you want to refer to the vector for name "name1", you can write
S.name1
and so on.
For example you can assign a new value to the 'name3' vector:
S.name3 = [1 2 3]
If the name is stored in a variable, that's easy to accommodate as well:
vector_name = 'name4';
% retrieval:
S.(vector_name)
% assignment:
S.(vector_name) = [1 2 3 4]
0 Comments
More Answers (1)
Walter Roberson
on 15 Dec 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);
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!