フィルターのクリア

Add a known column to a matrix 'n' times without a loop?

1 回表示 (過去 30 日間)
ken
ken 2011 年 5 月 22 日
Hi Guys!
Is there a way of qriting the script below without the loop? I'm sure there's a way but I can't find it in the help section or the internet.
I want to add a known column of numbers to a matrix 'n' times.
Thank you!
Ken
clear all
clc
a=zeros(5,6); % matrix a
[m,n]=size(a);
b=zeros(m,n); % matrix b
b(1:10)=[8 8 8 8 8 10 10 10 10 10];
for i=3:n;
b(:,i)=[1 2 3 4 5];
end
  4 件のコメント
Walter Roberson
Walter Roberson 2011 年 5 月 22 日
These days "for loops" are not necessarily slower, and in some cases are faster.
ken
ken 2011 年 5 月 22 日
Thanks for letting me know Walter

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2011 年 5 月 22 日
b(:,k:n) = (1:5)'*ones(1,n-k+1);
more
V = 1:5;
b(:,k:n) = V(ones(1,n-k+1),:).';
more more
b(:,k:n) = repmat(1:5,n-k+1,1).';
  3 件のコメント
Jan
Jan 2011 年 5 月 23 日
@Andrei: The ONES method is applied inside REPMAT also. Therefore I expect using it directly is faster, because the overhead of calling a function is avoided.
Usually a matrix with repeated rows wastes memory, because of the redundancy. Therefore a BSXFUN method can be faster: Do not create the matrix explicitely, but instruct BSXFUN to perform an operation by "inflating" the vector dynamically.
Andrei Bobrov
Andrei Bobrov 2011 年 5 月 23 日
Thank Jan for your comment

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

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2011 年 5 月 22 日
help repmat
  1 件のコメント
ken
ken 2011 年 5 月 22 日
Thanks Fangjun!

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by