Expand vectors of matrix, but a different number of times each vector

1 回表示 (過去 30 日間)
Fernando
Fernando 2012 年 5 月 9 日
Hi all,
I have the following problem. Consider a matrix of the form
Z =[1 0 0 0; 1 0 0 0; 1 0 0 0; 0 0 0 1; 0 0 0 1];
Because I'll use this later, consider the vector that sums the elements of the matrix by rows:
C=[3 0 0 2];
I would like to take every column in Z and expand it according to the elements in C, when the expansion when C=0 is just the column itself, to get
D=[1 1 1 0 0 0 0; 1 1 1 0 0 0 0;1 1 1 0 0 0 0;0 0 0 0 0 1 1;0 0 0 0 0 1 1];
Some things to consider. I have a lot of matrices "Z". In particular, they are defined in a structure way. This means that, for example, I have mk(i).Z where i goes from 1 to, say, 50. This means that I also have 50 vectors "C" (mk(i).C). Finally, the Z's have different dimensions that I don't know ex-ante (they are generated randomly within the code).
Any help would be great, thanks
Fernando

採用された回答

Sean de Wolski
Sean de Wolski 2012 年 5 月 9 日
z2 = cell2mat(cellfun(@(z,c)repmat(z,1,max(c,1)),num2cell(Z,1),num2cell(C),'uni',false))
Not sure why you need to do this though. It's going to take more memory to not get you any more information. If you could explain a little more, we might be able to help with a better way.
  1 件のコメント
Fernando
Fernando 2012 年 5 月 9 日
Thanks! I'll try to explain what I'm trying to do. Say you have data from two markets and you store the data as mk(1).data and mk(2).data. In each market I have a different number of stores (mk(1).n and mk(2).n) and this stores have a certain ownership structure. You could say that in the example above there are three stores of chain 1, zero of chains 2 and three and two o chain four. Then, when the chains decide prices, they have to consider the effect that that a change in prices of store 1 (owned by chain 1) will have on stores 2 and 3 of the same chain. This is captured by the new rows that where added.
Thanks for your help.

サインインしてコメントする。

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2012 年 5 月 9 日
C=[3 0 0 2];
D = arrayfun(@(x)[zeros(x==0),ones(x)],C,'un',0);
D = blkdiag(D{:});
D = D(any(D,2),:);
or
D = cell2mat(arrayfun(@(ii)Z(:,ii)*ones(1,C(ii)+(C(ii)==0)),1:numel(C),'un',0));

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by