Selecting Value in matrix already indexed

1 回表示 (過去 30 日間)
Raphaël
Raphaël 2018 年 5 月 15 日
コメント済み: Raphaël 2018 年 5 月 15 日
Hi, I'm trying to something relatively simple. Is there a way to select certain value in an already indexed matrix. Here is a simplified exemple of what I want to do.
A = rand(3);
B = @(x) A + x.^2; %Where x is a vector 3x1. Result is thus a 3x3 matrix.
C = @(x) B(x)(:,1:2); %I want C to be the first two columns of the result of B(x)
Obsiously, B(x)(:,1:2) isn't a valid way to write things. Is there a way to do this without finding a work around?
Thanks for the help.
RMT
  1 件のコメント
Stephen23
Stephen23 2018 年 5 月 15 日
@Raphael: is there a particular requirement to use anonymous functions? You could get around this quite easily by writing a normal function in an Mfile.

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

採用された回答

Stephen23
Stephen23 2018 年 5 月 15 日
編集済み: Stephen23 2018 年 5 月 15 日
Some options:
1. avoid the situation by defining a function in an Mfile. This is the simplest and probably most efficient solution.
2. call subsref directly to do the indexing:
>> A = rand(3);
>> Bf = @(x) bsxfun(@plus,A,x.^2);
>> Cf = @(x) subsref(Bf(x),substruct('()',{':',1:2}));
>> Bf(1:3)
ans =
1.1974 4.4016 9.1932
1.6292 4.8217 9.0481
1.6670 4.1590 9.4776
>> Cf(1:3)
ans =
1.1974 4.4016
1.6292 4.8217
1.6670 4.1590
3. Define an intermediate function to do the indexing:
>> A = rand(3);
>> Bf = @(x) bsxfun(@plus,A,x.^2);
>> If = @(M) M(:,1:2);
>> Cf = @(x) If(Bf(x));
>> Bf(1:3)
ans =
1.5517 4.7931 9.7715
1.0754 4.6154 9.4393
1.6711 4.5820 9.2449
>> Cf(1:3)
ans =
1.5517 4.7931
1.0754 4.6154
1.6711 4.5820
  1 件のコメント
Raphaël
Raphaël 2018 年 5 月 15 日
I like option 3, thanks.
But there's really no way to ask twice in a row an indexing. A(5)(3). I find it weird you don't have that option.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by