MATLAB Answers

0

how to replace elements in top third, middle third, and bottom third of matix

Marlon Izaguirre さんによって質問されました 2019 年 5 月 1 日
最新アクティビティ Nijita Kesavan Namboothiri さんによって 回答されました 2019 年 6 月 25 日
My task is the following:
Write a function called trio that takes two positive integer inputs n and m. The function returns a 3n-by-m matrix called T. The top third of T (an n by m submatrix) is all 1s, the middle third is all 2-s while the bottom third is all 3-s. See example below:
M = trio(2,4)
M =
1 1 1 1
1 1 1 1
2 2 2 2
2 2 2 2
3 3 3 3
3 3 3 3
This is the code that I wrote, but it only works for T = trio (4,3). I want my code to work for any input of n,m.
function T = trio (n, m)
T = randi (10, (3 * n) , m);
T ( 1:n , :) = 1;
T ( (n+1):(end-(n-1)) , :) = 2;
T ( (n+3):end, :) = 3;
end
How is it possible to call out only top third, middle third, and bottom third of any matrix?
Thank you in advance.

  0 件のコメント

サインイン to comment.

4 件の回答

回答者: James Tursa
2019 年 5 月 1 日
編集済み: James Tursa
2019 年 5 月 1 日
 採用された回答

Your row indexing is wrong.
The first n rows are 1:n which you have correct.
The second n rows indexing is n more that the first set, so simply add n: n + (1:n)
The third n rows indexing is n more than the second set, which I will let you figure out (it's pretty simple)

  1 件のコメント

Thank you so much James!!!! I was able to figure out the third n rows.
I really appriciate your time.

サインイン to comment.


回答者: AYUSH GURTU 2019 年 5 月 28 日

function T = trio (n, m)
T = randi (10, (3 * n) , m);
T (1:n,:) = 1;
T ((n+(1:n)),:) = 2;
T (n+(n+(1:n)):end,:) = 3;
end

  0 件のコメント

サインイン to comment.


回答者: mayank ghugretkar 2019 年 6 月 5 日

function T=trio(n,m)
T(3*n,m)=3; % or you can use random no. generation...but since we are assigning alues anyway , this vl work fine !
T(1:n,:)=1;
T((n+1):2*n,:)=2;
T((2*n+1):3*n,:)=3;
end
hope this'll help, welcome !

  0 件のコメント

サインイン to comment.


回答者: Nijita Kesavan Namboothiri 2019 年 6 月 25 日

function T = trio (n, m)
T = randi (10, (3 * n) , m);
T ( 1:n , :) = 1;
T ( (n+1):(2*n) , :) = 2;
T ( ((2*n)+1):end, :) = 3;
end

  0 件のコメント

サインイン to comment.



Translated by