How can I loop over a series of vectors - X0, X1, X2, X3... etc - and evaluate a function on each vector?
16 views (last 30 days)
Show older comments
Hi,
I've tried digging around for a way to do this, but the nearest question to mine was unanswered, so I'm hoping that there's someone who knows how to do this.
So I have 1000 text files containing two columns of data, but different numbers of rows - the (x,y) values for a given data set.
I've managed to import these files into my workspace, where they're stored as vectors and given names from X1 to X1000.
I've created a function - called parameter(x) - that can evaluate one of these vectors and give me a number. I'd like to collect all these numbers together in a vector.
Rather than evaluate parameter 1000 times by hand,I thought if I could loop over the vectors in a script and evaluate parameter(Xi), I could put this result in the ith column of a vector, i.e. bvector[i] = parameter(Xi).
The problem arises when I try to evaluate parameter(Xi). I've been using sprintf to create the vector name and then evaluate:
bvector = [1:1000];
for i = 1:1000
name = sprintf('X%d',i)
j = i+1;
bvector(j) = parameter(name);
end
I get an error saying that parameter can't be evaluated, and I realised that this is because (e.g) X12 just a name, and has no link to the vector X12.
I've tried varies ways of getting it to do what I want, like using eval(), but I'm a bit new at this, and I'm not sure how to proceed. Any ideas?
0 Comments
Answers (3)
Daniel Shub
on 25 Jul 2012
First lets generate some data with problematic naming:
N = 10;
x1 = rand(1, 1);
x2 = rand(2, 1);
x3 = rand(3, 1);
x4 = rand(4, 1);
x5 = rand(5, 1);
x6 = rand(6, 1);
x7 = rand(7, 1);
x8 = rand(8, 1);
x9 = rand(9, 1);
x10 = rand(10, 1);
Now lets work around the naming problem
temp = cellstr(arrayfun(@(n)sprintf('x%d', n), 1:N, 'UniformOutput',false));
save('myx.mat', temp{:});
clear(temp{:});
x = load('myx');
Now you no longer have x1, x2, ..., xN in the workspace, but rather just structure x with fields x1, x2, ..., xN. You can now get what you want in a for loop:
for ii = N:-1:1
bvector(ii) = parameter(x.(['x', num2str(ii)]));
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!