Blake
Blake

Reputation: 7547

Concatenate strings as a variable in matlab?

I have data sets stored to several variables like: p1_5, p1_7,p1_9....p1_19, and I want to calculate the std() of each data set. Now how to do it in a for loop in matlab? How to concatenate 'p1_' to n, but still keep it as a variable but not string?

for n = 5:2:19
    std(p1_??);  
end

Upvotes: 1

Views: 139

Answers (2)

cyborg
cyborg

Reputation: 10139

You could put them in a cell array. Even better, if they have the same dimensions, stack them in a matrix.

Upvotes: 2

Dan
Dan

Reputation: 45752

You can use eval for this:

for n = 5:2:19
    eval(['std(p1_', num2str(n), ')']);  
end

But you should probably consider restructuring your code to not have to. Could you store all your p1s in a 3D matrix or a cell array?

Upvotes: 3

Related Questions