0

I want to create cells in matlab like the following:

 Q{1,1,1}=1;
 Q{1,1,2}=1;
 Q{2,2,1}=1;
 Q{2,1,2}=1;

However, I do not want to create this manually. In my application I have some vectors, one of which can be: x=[1 2 3 4]

And with this vector x I want to create

 P{1,2,3,4}=1 

So the vector x kind of dictates the coordinates of the cell (sorry for bad english).

Since I dont know the length of the vector (it can change from case to case) I cannot do this:

       P{x(1,1),x(1,2),x(1,3),x(1,4)}=1;

What can I do here?

EDIT: I put the cells content with number "one" just for an example. The content of cell its gonna be linear matrix variable generated by the function sdpvar from the yalmip toolbox.

gustavoreche
  • 205
  • 4
  • 12

2 Answers2

1

First, if you only have numeric content perhaps a matrix is better then a cell.


To populate the spaces within a cell with a certain input you could do the following:

x = [1 2 3 4];
P(x) = {1}
P = 
    [1]    [1]    [1]    [1]

This also works when a index is skipped

x = [1 2 4 5]
P(x) = {1}
P = 
    [1]    [1]     []    [1]    [1]

To create your Q cell you should preallocate it to get the correct size, then you could use sub2ind to point out correct indexes

Q = cell(2,2,2)
% To populate all with 1
Q(:) = {1}
Q(:,:,1) = 
    [1]    [1]
    [1]    [1]
Q(:,:,2) = 
    [1]    [1]
    [1]    [1]
% To populate only a certain indexes
idx = sub2ind( size(Q), [1 1 2 2], [1 1 2 1], [1 2 1 2]);
Q(idx) = {1}
Q(:,:,1) = 
    [1]     []
     []    [1]
Q(:,:,2) = 
    [1]     []
    [1]     []
NLindros
  • 1,683
  • 15
  • 15
  • He wants to fill a particular index not all indexes @nilZ0r – Optimus 1072 Nov 22 '16 at 12:14
  • @Optimus1072 Yes, and that is also what most of my code examples does. The `Q(:)` was merly done as an example to compare the `Q(idx)` with. I think the comments clarifies the difference. – NLindros Nov 22 '16 at 13:21
0

I am not sure you can do that without resorting to eval:

>>> x=[1,2,3,4];
>>> value=1 % or whatever you need here
>>> cmd=sprintf('%s%s%s','P{', strjoin(arrayfun(@(a) num2str(a),x,'UniformOutput',false),','), '}=value')
cmd = P{1,2,3,4}=1
>>> eval(cmd)
P = {1x2x3x4 Cell Array}
>>> P{1,2,3,4}
ans =  1
>>>
damienfrancois
  • 52,978
  • 9
  • 96
  • 110
  • in your solution u are writing the number "1". This number is just an example and I dont want to write it manually, in fact I dont want to write a number to P. Mine 'P' should be an Linear Matrix Variable which I set using yalmip toolbox. I'm sorry for any trouble, but I wanted to simplify the question. – gustavoreche Nov 22 '16 at 09:57