How to loop through a series of variables, named with strings but including numbers? -Undefined function or variable
3 views (last 30 days)
Show older comments
Hi, I'm an undergraduate researcher trying to figure out how to generate values from a bunch of different datasets. I have 12 matrices from 12 different files, each of which has two fields. The fields in different matrices are the same except for a number tagged onto the end. So the first matrix has fields a_1 and b_1, the second has fields a_2 and b_2, the third has fields a_3 and b_3, etc. I want to multiply the first field of each matrix by the second field of the same matrix and sum it, and I'd like to do this in a loop. Right now I have this:
for i = 1:12; x_i = sum(a_i'*b_i'); A{i} = [i; x_i]; end
I'm trying to get a final matrix A with the numbers 1:12 as field one and the corresponding x value in field 2.
I have very little experience with loops in matlab. Thanks so much for your help!
2 Comments
KSSV
on 19 Apr 2017
What you are trying is allocating a dynamic naming of variables which is not at all suggested and required. You have the matrices in file, you can straight a way read them into 3D matrix and do what you want.
Stephen23
on 19 Apr 2017
Edited: Stephen23
on 19 Apr 2017
@Niky Taylor: can you please upload a sample file by making a new comment and clicking the paperclip button. Most likely the best solution would be to import that data into one array, such as an ND array or perhaps a non-scalar structure.
You write that "So the first matrix has fields a_1 and b_1": is the matrix a structure (only structures have fields), or is the matrix numeric type? You write that "12 matrices from 12 different files": are these .mat files, or some other file format?
If you upload your data then we can see exactly what you are trying to explain.
See Also
Categories
Find more on Characters and Strings 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!