## Construct a reference to a matrix where the matrix name is the value of a variable

on 9 Apr 2013

### Teja Muppirala (view profile)

I want to construct a matrix reference from information contained in a set of variables. Example: say I want to set a matrix with these values:

```fData = saaData(:, 16)
```

However, the statement is part of a for loop, and both the column and the particular matrix being referenced change on each pass. They are specified by a pair of variables:

```fctSource = factors{i, 2};
fctIdx = factors{i, 3};
```

where on this pass, factors{i, 2} = saaData and factors{i, 3} = 16.

How can I construct a command, using fctSource and fctIdx, that will return the column vector given by saaData(:, 16)?

## Products

No products are associated with this question.

### Teja Muppirala (view profile)

on 9 Apr 2013

If you need to reference a variable with a dynamic name based on a string, you'd generally call EVAL. That being said, doing these sorts of manipulations with EVAL can often get confusing, and is usually not a efficient way to solve a problem.

```saaData = rand(3,16)
```
```if exist(factors{2},'var') %Make sure it's actually a variable...
string = [factors{2} '(:,' num2str(factors{3}) ')'];
fData = eval( string )
end
```

William

### William (view profile)

on 9 Apr 2013

That's done it, thanks for the answer.

on 9 Apr 2013

William

### William (view profile)

on 9 Apr 2013

I think I'm missing something on how to use that. This seems to be advice about creating a set of variables. In my case, I'm trying to construct a matrix from columns in a number of other matrices. (The example I gave above is a touch simplified; where it says fData = saaData(:, 16), what I properly want is fData(:, 1) = saaData(:, 16). The other columns will be set in the same way, referencing different matrices, in the subsequent passes of the for loop.)

Am I missing a connection between creating variables and creating matrices, or should I try a different approach?

Walter Roberson

### Walter Roberson (view profile)

on 9 Apr 2013

The techniques for creating a set of variables are closely related to the techniques for using a set of variables.

And you missed the big point of the beginning: DON'T DO THAT! Store your variables in indexable forms instead of using different variable names.

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi