How to concatenate table variables with underscores in their name
Afficher commentaires plus anciens
I have variables like B1_1_3(53x1) B2_1_3(53x1) until B56_1_3(53x1) stored in my table A. I want to concatenate them to receive a new vector(53x56). I tried:
for k in 1:56
a = [A.B{k}_1_3, A.B{k}_1_3];
end
However this does not work. Any suggestions? Thank you in advance!
1 commentaire
infinity
le 23 Juil 2019
What do you mean by "concatenate them to receive a new vector (53x56) "?
For example,
A = [1 2 3]
B = [1 2 3 4]
what is your output of a new matrix?
Réponse acceptée
Plus de réponses (1)
You could use eval for this. Assuming your data in the table is numeric and you want a matrix as result:
a = zeros(53,56);
for i=1:56
eval(['a(:,i) = A.B' num2string(i) '_1_3'])
end
Edit: It has been pointed out that using eval is unnecessary here and bad in general. See the comments below for better solutions.
I just considered this to be closest to what OP was trying to do, but there are certainly better methods.
3 commentaires
Guillaume
le 23 Juil 2019
Do not use eval. Do not use eval. Do not use eval!
We spend enough time fixing people code that use eval. Why Variables Should Not Be Named Dynamically (eval)
And it's completely unnecessary as well. The same as you've done without eval:
varnames = compose('B%d_1_3', 1:56);
a = A{:, varnames};
So much easier to read, a hell of a lot faster, clear error messages if there's a problem (like one of the variable doesn't actually exist), and easy to debug.
On that last point, did you notice the bug in your eval line? (hint: you only fill one column of a).
Guillaume
le 23 Juil 2019
Gah! Why did you accept this answer. Again, eval is bad! extremely bad!. See the link in my comment above for all the ways that it is bad.
Do not use eval and certainly not for this. I've demonstrated a much more reliable method (and simpler, and faster, and etc... read the link).
Adam's method is even more reliable in that it doesn't assume that variables 1 to 56 do exist but check which ones exist.
Catégories
En savoir plus sur Tables dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!