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

60 次查看(过去 30 天)
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
John D'Errico 2023-5-25
编辑: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 个评论
James Tursa
James Tursa 2023-5-25
编辑: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 =
Structure address = 1dd33fd5fc0
m = 1
n = 10
pr = 1dd1e418b20
1 2 3 4 5 6 7 8 9 10
>> v(end)=[]
v =
Structure address = 1dd33fd7a00
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by