How to get a subarray from a matrix

Hi. I am looking to solve this Question: Write a function called top_right that takes two inputs: a matrix N and a scalar non-negative integer n, in that order, where each dimension of N is greater than or equal to n. The function returns the n-by-n square array at the top right corner of N.
So I am looking to take the top right portion of matrix N to get a subarray that is n by n units. I thought the code might look like this:
function M = top_right(N,n)
M = N(end-n+1:end, 1:n);
However, this gives me the bottom left of the matrix and i want the top right.

댓글 수: 6

yasin Sanjar
yasin Sanjar 2017년 2월 22일
try M= [N(1:n,end-n+1:end)]
aklapaz
aklapaz 2017년 3월 17일
Hi Sanjar, could you explain the logic behind this part of your script?: end-n+1:end
Thanks
Karthik  Subramanian
Karthik Subramanian 2017년 5월 16일
Lets say you have 5 columns. Top right and n=2 means you need last two columns. So you should count till end and you start from the last before column which is end-n+1 = 5-2+1 = 4 . As you need columns 4 and 5.
Vijay Ramanathan
Vijay Ramanathan 2017년 10월 2일
I was trying M= [N(1:n,end-n+1:end)] with M= [N(1:n,end-n:end)] before i saw your answer. I thought it wont apply for all but later it did :) Thanks Karthik and Yasin
Stephen23
Stephen23 2017년 10월 2일
In all of the above comments the square brackets are superfluous.

댓글을 달려면 로그인하십시오.

답변 (3개)

James Tursa
James Tursa 2016년 8월 5일
편집: James Tursa 2016년 8월 5일

4 개 추천

Switch your row and column indexing. E.g.
M = N(1:n,end-n+1:end);
Star Strider
Star Strider 2016년 8월 5일

2 개 추천

That’s different than the wording of your earlier Question.
As far as the indexing code, see if this does what you want:
N = randi(99,8,6) % Argument Matrix
[R,C] = size(N);
min_dim = min(R,C);
n = randi(min_dim-1) % Argument Parameter
M = N(1:n, C-n+1:C) % Return Top Right Corner Square Matrix
N =
79 65 20 86 17 8
10 49 4 80 97 52
26 78 74 58 71 10
34 71 50 19 50 81
68 90 48 24 47 81
14 89 90 88 6 72
72 34 61 3 68 15
11 70 62 49 5 66
n =
3
M =
86 17 8
80 97 52
58 71 10
Aakriti Mittal
Aakriti Mittal 2018년 5월 30일

0 개 추천

function N=top_right(M,n) T = M(1:n,1:n); N=T; Try this code...Hopefully it will work.. Aakriti

댓글 수: 1

  • please learn to format your answer
  • You're answering a two year old question. Hopefylly, the OP is still not waiting for an answer
  • Your function returns the top left portion of the matrix, not the top right
  • What is the point of
T = ...;
N = T;
? Why not write directly
N = ...;
and not have an intermediate variable that serves zero purpose?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2016년 8월 5일

댓글:

2018년 5월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by