Making new matrix with specific rows

14 ビュー (過去 30 日間)
Brandon
Brandon 2023 年 7 月 24 日
コメント済み: dpb 2023 年 7 月 24 日
The following code as an example, how would I go about making a new separate table with only the rows with a specific value in a column?
ie: How would I go about making the new table with only 'ABC' in the first column?
I've tried the method of using a for loop and manually checking line by line but the file that I actually have to do this for is much larger and takes way too long so I was wondering if there's a faster way, maybe with ':'
A = {
'ABC' 1.0000 5.5000
'ABC' 2.0000 1.2000
'DEF' 3.0000 6.4000
'ABC' 4.0000 3.7000
'XYZ' 5.0000 3.6000
'PQT' 6.0000 9.6000};

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 7 月 24 日
A = {
'ABC' 1.0000 5.5000
'ABC' 2.0000 1.2000
'DEF' 3.0000 6.4000
'ABC' 4.0000 3.7000
'XYZ' 5.0000 3.6000
'PQT' 6.0000 9.6000};
%Compare the 1st column of the char array/string 'ABC'
idx = strcmp(A(:,1),'ABC')
idx = 6×1 logical array
1 1 0 1 0 0
%Create the new array corresponding to the indices
B = A(idx,:)
B = 3×3 cell array
{'ABC'} {[1]} {[5.5000]} {'ABC'} {[2]} {[1.2000]} {'ABC'} {[4]} {[3.7000]}

その他の回答 (1 件)

dpb
dpb 2023 年 7 月 24 日
Use <logical indexing>, a basic MATLAB syntax/idiom. If this isn't something you're not already familiar with, I'd suggest reading through the <Language Fundamentals> section of the introductory help/documentation.
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 24 日
I strongly recommend you go through the free MATLAB Onramp tutorial to learn the essentials of MATLAB.
dpb
dpb 2023 年 7 月 24 日
While it seems like wasting time that could be coding; you'll progress towards the end goal far more effectively if you learn at least the rudiments of the language (and its idiosyncracies) first; the time spent either in the "Getting Started" or the "On Ramp" tutorials will pay back the investment many times over.

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

カテゴリ

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