Target just the last added entries to a matrix

조회 수: 1 (최근 30일)
Vance Blake
Vance Blake 2019년 8월 30일
댓글: Vance Blake 2019년 9월 1일
Hey, I am working with matrices and I wanted to know if there is a standard way/code to target just the last added entries to a matrix. I used the general syntax for appending data points to a matrix (A= [A;B]) and I wanted to know if there was an analogous general method for targetting the last added entries into a matrix. For example, I append 4 sets of coordinates to a matrix and now I want to call just those 4 sets from the matrix and use them for next step in my code. Any help is greatly appreciated.
  댓글 수: 4
Guillaume
Guillaume 2019년 8월 30일
There is always another way, but your question is not particularly clear.
A(end-n:end, :)
will give you the last n+1 rows of the matrix.
Note that growing a matrix by appending rows in a loop is slow. If you know beforehand how many rows the final matrix is going to be, then preallocating the matrix is a lot more efficient.
Vance Blake
Vance Blake 2019년 8월 30일
Yeah I know that growing dynamically is slow (matlab kindly reminds me every time i run my code) but unfortunately I don't know how big the matrix will be beforehand. But Im not appending the sets of coordinates to the matrix during the loop but after it has been completed.
@Guillaime does your solution only work with a loop ??

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

채택된 답변

Guillaume
Guillaume 2019년 8월 30일
As commented:
A(end-n:end, :)
will give you the last n+1 rows of the (2D) matrix.
does your solution only work with a loop
Why do you think that? There's no loop involved in that line. It's basic matrix indexing using the end keyword.
  댓글 수: 3
Guillaume
Guillaume 2019년 9월 1일
Have you read the documentation page I linked?
This is really basic indexing. As everything in matlab, the name of the variable is irrelevant. You can call them whatever you want or replace the variable by a hardcoded constant
A(end-n:end, 1) %returns the last n+1 rows of A
A(end-10:end, 1) %returns the last 11 rows of A
somename(end-someothername:end, 1) %returns the last someothername+1 rows of somename
Vance Blake
Vance Blake 2019년 9월 1일
My bad didnt notice the link but thanks for the help.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by