Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 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 Reply

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...