Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

matlab - how to replicate an array

I want to make a function like this

>> matdup([1 2],3,4)            %or any other input that user wish to enter
ans= 

 1     2     1     2     1     2     1     2
 1     2     1     2     1     2     1     2
 1     2     1     2     1     2     1     2

I am stuck in my code. My logic:

m = matdup(input,row,col)
for i = 1:row
        for j = 1:col
            m(i, j)= input;

This is producing this:

>> matdup(1,2,2)
ans=

      1 1
      1 1

But failed at this:

>> matdup([1 2],3,4)

error at console:

Subscripted assignment dimension mismatch.

    Error in ==> matdup at 6
                m(i, j)= input

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Method 1: Are you allowed to use ones? Try this -

A = [1 2]

rowIdx = [1 : size(A,1)]';
colIdx = [1 : size(A,2)]';

out = A(rowIdx(:, ones(3,1)), colIdx(:, ones(4,1)))

Output

out =

     1     2     1     2     1     2     1     2
     1     2     1     2     1     2     1     2
     1     2     1     2     1     2     1     2

Method 2: Are you allowed to use bsxfun and permute? Try this for the same result -

A = [1 2]
row_mapped = bsxfun(@plus,A,zeros(3,1))
out = reshape(bsxfun(@plus,row_mapped,permute(zeros(4,1),[3 2 1])),[3 8])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...