MATLAB Answers

Indexed Assignment on the Right Side

1 ビュー (過去 30 日間)
Sinan Islam
Sinan Islam 2020 年 11 月 17 日
コメント済み: Sinan Islam 2020 年 11 月 18 日
I am calling function f(x) that returns a matrix of 100 columns.
All what I need is just the 10th column. So I need one vector from the whole returned matrix.
I need to get rid of 99 columns and retain only the 10th column.
In Julia, this can be done by:
columnTen = f(x)[:,10]
I am dying to do the same thing in MATLAB.
Not sure why this simple operation seems impossible.

採用された回答

Walter Roberson
Walter Roberson 2020 年 11 月 17 日
columnTen = struct('fx', rand(7,20)).fx(:,10) %needs R2019b or later IIRC
columnTen = 7×1
0.9090 0.8635 0.0364 0.2788 0.2503 0.1882 0.7757
columnTen = subsref(rand(7,20), substruct('()', {':', 10}))
columnTen = 7×1
0.3391 0.0112 0.5269 0.0961 0.5855 0.0371 0.4590
But if you are permitted an initialization beforehand:
Col = @(M,n) M(:,n); %once
ColumnTen = Col(rand(7,20), 10)
  1 件のコメント
Sinan Islam
Sinan Islam 2020 年 11 月 18 日
Verbose but working. I hope MATLAB make it as simple as other languages. Thank you!

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2020 年 11 月 17 日
Y = f(x);
columnTen = Y(:,10);
  1 件のコメント
Sinan Islam
Sinan Islam 2020 年 11 月 17 日
That is two steps. I need to make the assignment on the fly, in just one line (one operation). I am working with characters. I dont have the option to work on multiple lines (multiple operations). But thanks anyway!

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

Community Treasure Hunt

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

Start Hunting!

Translated by