Got Questions? Get Answers.
Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
from smaller to larger matrix

Subject: from smaller to larger matrix

From: Jalen Xiaojing

Date: 25 Mar, 2009 18:54:02

Message: 1 of 2

I need to generate a large matrix from a smaller one, by replicating each row of the smaller matrix. The number of replications is defined by a vector, with the same length as the number of rows in the smaller matrix.

For example,
smallmat = [2 3
                 4 5
                 6 7]
vec = [3 2 2]

Then I need to replicate smallmat(1,:) by vec(1) times; smallmat(2,:) by vec(2) times and smallmat(3,:) by vec(3) times, and get

largemat=[ 2 3
                2 3
                2 3
                4 5
                4 5
                6 7
                6 7];

The easiest way is to write a loop, but that is too slow. How to efficiently do this, with the fastest way?

Subject: from smaller to larger matrix

From: Roger Stafford

Date: 25 Mar, 2009 19:51:01

Message: 2 of 2

"Jalen Xiaojing" <tulipgarden@gmail.com> wrote in message <gqduka$9lt$1@fred.mathworks.com>...
> I need to generate a large matrix from a smaller one, by replicating each row of the smaller matrix. The number of replications is defined by a vector, with the same length as the number of rows in the smaller matrix.
> ......

  Assuming 'vec' is a column vector,

 p = zeros(size(vec,1),1);
 p(cumsum(vec)) = 1;
 p = cumsum([1;p(1:end-1)]);
 largemat = smallmat(p,:);

  However, you should compare times with a for-loop method. It might be faster.

Roger Stafford

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us