0

I tried to replace:

[BB{1,1}(combs(ii,1),:) BB{1,2}(combs(ii,2),:) BB{1,3}(combs(ii,3),:)]

by [BB{1,1:end}(combs(ii,1:end),:)]

but I get this error message: ??? Bad cell reference operation.

How I can solve this problem?

bzak
  • 563
  • 1
  • 8
  • 21

2 Answers2

2

The solution you tried:

[BB{1,1:end}(combs(ii,1:end),:)]

Isn't valid because you can't index multiple cells at the same time. I'm guessing that the reason you tried that is because you want to make work on matrices with different numbers of columns. It's possible, but you have to use cellfun to index each cell separately.

cellfun(@(x)x(combs(ii,:)), BB(1,:))

That will let you work with matrices of any arbitrary size in the 2nd dimension.

UPDATE:

I'm not sure if I understood what you were trying to do. In my last solution, I thought you were trying to get the entire iith row of each matrix in BB. Looking at the original code, there is a correspondence between the second dimension of BB and the second dimension of combs. Here is another possibility that preserves that correspondence:

A = cellfun(@(x,n)x(combs(ii,n),:), BB(1,:), num2cell(1:size(BB,2)), 'UniformOutput', false);
cat(2,A{:})

Note that this will only work if the second dimension of BB and combs are the same size.

  • ??? Error using ==> cellfun Input #2 expected to be a cell array, was double instead. – bzak Jan 09 '15 at 10:56
  • Oops. Sorry. That's because I used curly brackets instead of parentheses. I fixed it. – Pet Detective Jan 09 '15 at 14:41
  • Now I do not get an error message, but instead of getting a matrix 12x7 , I get a matrix 12x3 !! With [BB{1,1}(combs(ii,1),:) BB{1,2}(combs(ii,2),:) BB{1,3}(combs(ii,3),:)], I get a matrix 12x7. – bzak Jan 09 '15 at 21:28
  • I think this will fix that: cellfun(@(x,n)x(combs(ii,n),:), BB(1,:), num2cell(1:size(BB,2))) – Pet Detective Jan 09 '15 at 23:31
  • ??? Error using ==> cellfun Non-scalar in Uniform output, at index 1, output 1. Set 'UniformOutput' to false. Error in ==> CC(ii,:) = cellfun(@(x,n)x(combs(ii,n),:), BB(1,:), num2cell(1:size(BB,2))); – bzak Jan 09 '15 at 23:35
  • I'm really trying, haha. You can use `'UniformOutput',false` like the error message says, but then you will get a cell array of numerical arrays instead of a numerical array. I updated the solution to do that and then collapse the cell array into a numerical array. Maybe that will do it. – Pet Detective Jan 09 '15 at 23:42
1

In addition to @Alan's answer, you can copy the cell contents into a temporary double array using the comma-separated nature of cell arrays and then index:

temp   = [BB{1,1:end}];
values = temp(combs(ii,1:end),:);

It would be nice if we could index the array literal itself like [BB{1,1:end}](combs(ii,1:end),:), but MATLAB doesn't have nice syntactic sugar for that operation (though there is an, in my opinion, ugly way to do it).

Community
  • 1
  • 1
TroyHaskin
  • 8,361
  • 3
  • 22
  • 22