Truncate an array in a specified dimension in Matlab

105 ビュー (過去 30 日間)
N Kando
N Kando 2016 年 6 月 29 日
コメント済み: Doug 2020 年 7 月 4 日
In Matlab, does a pad command exist, which also pads in the negative dimension (therefore removing indices in a specified dimension)?
[Edit: I knew something did this - fft does this for the input, but it also takes the fft.]
I have a function which can receive input data x in n_dim dimensions.
I would like to remove all but n datapoints from a user specified dimension dim. I could use shiftdim to always make the specified dimension the first dimension; however, how do I code such that I do not need a finite number of colons to represent the dimensions of the input data x?
x = rand(01,12,01); % n_dim = 1
y = rand(04,12,01); % n_dim = 2
z = rand(04,12,07); % n_dim = 3
n = 3
see:
dim = 1
y = y(1:n, : );
z = z(1:n, :, : ); % Note that extra colons are needed depending on n_dim.
or:
dim = 2
x = x( 1:n );
y = y(:, 1:n, );
z = z(:, 1:n, : ); % Note that extra colons are needed depending on n_dim.
Do I need to use the shiftdim command to place dim in the first dimension, and then place the 1:n within the eval command along with a string variable which contains as many |,:|s as needed?
Note: Also asked on superuser.

採用された回答

Prasad Mendu
Prasad Mendu 2016 年 7 月 6 日
Hello N Kando,
Yes, the solution that you proposed at the end of your question can be used to achieve it. Another way to achieve this is to declare all the data points other than the first n data points as empty ones.
For example, instead of doing
z = z(:,1:n,:);
we can do
z(:,n+1:end,:)=[];
  2 件のコメント
Xuelei Lin
Xuelei Lin 2019 年 3 月 19 日
but, if the number of dimension is not specified, how to do that. For example, when length(size(z)) is not specified.
Doug
Doug 2020 年 7 月 4 日
The only way I've found is a bit of a dirty hack because it requires 'eval' -- but it works:
A=rand(3,4,5,6);
indstring=repmat('1:end-1,',[1 ndims(A)]);
indstring(end)=[];
eval(['A=A(' indstring ');']);
size(A)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by