필터 지우기
필터 지우기

Sum of row and column #?

조회 수: 5 (최근 30일)
Rachel Dawn
Rachel Dawn 2018년 2월 15일
답변: Matt J 2018년 2월 15일
Say I ask the user to input the size of a square matrices, n.
And say I want each element of this matrix to be the sum of the row # it's in & the column # it's in. So, for n =2:
2 3
3 4
Is there some Matlab function I could use to calculate each of those elements and display the above as a matrix?

답변 (4개)

Matt J
Matt J 2018년 2월 15일
편집: Matt J 2018년 2월 15일
result=(1:n).'+(1:n);
or for older MATLAB versions,
result = bsxfun(@plus,(1:n).',(1:n));

KSSV
KSSV 2018년 2월 15일
편집: KSSV 2018년 2월 15일
n = 2 ;
x = 1:n ;
row = repmat(x',1,n) ;
col = repmat(x,n,1) ;
iwant = row+col
Or
x = 1:2*n ;
ind = reshape(x,n,n) ;
[I,J] = ind2sub([n n],ind) ;
iwant = I+J
  댓글 수: 1
Rachel Dawn
Rachel Dawn 2018년 2월 15일
hi! Thank you very much. Could you elaborate on what each line of your code is actually doing/calculating? Sorry, I'm new to Matlab and unfamiliar with all those terms. I tried looking them up but Matlab instructions are quite complicated.

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


John D'Errico
John D'Errico 2018년 2월 15일
편집: John D'Errico 2018년 2월 15일
Matt's answer of
result=(1:n).'+(1:n);
is the best way, at least in current versions of MATLAB, because it is most clear what it is doing. But this only applies in 2017 releases and beyond.
Other solutions are less clear, but pretty simple. For example, this should be almost as obvious:
[i,j] = meshgrid(1:n);
result = i + j;
Or
result = cumsum(ones(n),1) + cumsum(ones(n),2);
Or
result = repmat(1:n,n,1) + repmat(1:n,n,1).';
Any of these should be quite clear, and all are equally valid. If unclear still, then it really is time to start reading the getting started tutorials in MATLAB. If you do not follow what they did, then look at each piece of the code. See what it does for some value of n. Read the documentation, perhaps for meshgrid, repmat, bsxfun, cumsum, etc., as appropriate. You won't learn MATLAB until you start reading the documentation.

Matt J
Matt J 2018년 2월 15일
Too bad hankel() isn't MEX-implemented. A MEX-optimized implementation of the following would be O(n),
result = hankel( 2:n+1,n+1:2*n)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by