# Is it possible to truncate a vector to form one of lower dimension?

33 ビュー (過去 30 日間)
Charles 2023 年 5 月 25 日

Is there a way to truncate a vector to eliminate the end terms? For example, a=[1;2;3;4;5;6;7;8;9], I want b=[1;2;3;4;5]. Is there a way to form b from a by truncating the last four terms of a?

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

### 回答 (2 件)

John D'Errico 2023 年 5 月 25 日

You have two choices. First, you can extract the elements you want. Or you can delete the elements you wnat to drop. For example:
V = primes(40)
V = 1×12
2 3 5 7 11 13 17 19 23 29 31 37
Now, drop the last 4 elements.
n = 4;
% This deletes the elements of V that you want to delete, and does so
% "in-place", in the sense that we do not assign a new vector.
V(end + (1-n:0)) = []
V = 1×8
2 3 5 7 11 13 17 19
Next, we can decide to extract all but the last n elements. I'll just use the last version of V.
V = V(1:end - n)
V = 1×4
2 3 5 7
In each case, we can see that the final 4 elements of V were dropped from V. As I said though, you can think of the second case as where I extracted the elements I wanted to save, while in the first case, I indicated the elements I wanted to delete.
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
James Tursa 2023 年 5 月 25 日

For clarification, to my knowledge MATLAB always allocates new memory when an indexed assignment results in a different size. E.g.,
>> format debug
>> v = 1:10
v =
m = 1
n = 10
pr = 1dd1e418b20
1 2 3 4 5 6 7 8 9 10
>> v(end)=[]
v =
m = 1
n = 9
pr = 1dd2de51500
1 2 3 4 5 6 7 8 9
You can see that even though we only deleted the last element, the data pointer pr changed, indicating that MATLAB allocated new memory and did a data copy of the rest. Maybe MATLAB could have been smarter and simply changed the dimensions directly in this case since that would only waste one element of memory, but it doesn't. The only way to delete trailing elements and retain the same data memory block (which is faster since no data copy is involved) is by unofficial hacking into the variable header and resetting the dimensions directly via a mex routine. This used to be possible on older versions of MATLAB, but later versions of MATLAB hide the shared data copies of variables from the user so even this is no longer possible.

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

Diwakar Diwakar 2023 年 5 月 25 日
You may try this code:
a = [1;2;3;4;5;6;7;8;9];
b = a(1:end-4);

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

### カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by