Is it possible to truncate a vector to form one of lower dimension?
42 ビュー (過去 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?
0 件のコメント
回答 (2 件)
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)
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 件のコメント
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
2023 年 5 月 25 日
You may try this code:
a = [1;2;3;4;5;6;7;8;9];
b = a(1:end-4);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!