How to use tril function on only specific columns in a large matrix?

2 ビュー (過去 30 日間)
Zuha Yousuf
Zuha Yousuf 2020 年 3 月 19 日
コメント済み: Zuha Yousuf 2020 年 3 月 19 日
So I have a very large matrix (31413 rows, 950 columns). I want to use the tril function on columns 2 till 10, and then from 12 to 20, and then from 22 to 30, and so on until the end of columns.
I need something like this
[col1 col2...col10 col11 col12...col20 col21 col22...col30 and so on]
where the columns in between have tril function used on them.
Is there any way I can do this??

採用された回答

Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 19 日
編集済み: Sriram Tadavarty 2020 年 3 月 19 日
Hi Zuha,
You can use a for loop as below and it does what is required:
m = rand(31413,950);
for i = 2:10:size(m,2)
m(:,i:i+8) = tril(m(:,i:i+8));
end
Hope this helps.
Regards,
Sriram
  1 件のコメント
Zuha Yousuf
Zuha Yousuf 2020 年 3 月 19 日
Thank you so much! I really appreciate it.

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

その他の回答 (1 件)

David Goodmanson
David Goodmanson 2020 年 3 月 19 日
Hi Zuha,
here's another, more vectorized version
m = rand(31413,950);
[r c] = size(m);
[jj ii] = meshgrid(1:c,1:8); % ii row jj col
ind = ii<mod(jj-1,10);
m18 = m(1:8,:);
m18(ind) = 0;
m(1:8,:) = m18;
It's faster than the for loop version, which is not a big deal since Sriram's code only takes 0.2 sec, and that code is more self-explanatory.
  1 件のコメント
Zuha Yousuf
Zuha Yousuf 2020 年 3 月 19 日
Thanks so much David! This approach makes sense to me too.

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

カテゴリ

Help Center および File ExchangeLinear Algebra についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by