Is it possible to truncate a vector to form one of lower dimension?
66 views (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
John D'Errico
on 25 May 2023
Edited: John D'Errico
on 25 May 2023
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)
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)) = []
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)
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 Comment
James Tursa
on 25 May 2023
Edited: James Tursa
on 25 May 2023
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
on 25 May 2023
You may try this code:
a = [1;2;3;4;5;6;7;8;9];
b = a(1:end-4);
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!