replace long string of variables

3 ビュー (過去 30 日間)
Cristian Martin
Cristian Martin 2022 年 6 月 1 日
コメント済み: Cristian Martin 2022 年 6 月 1 日
Hi,
I have a script like below. The problem is that I must to create until index50, how can I write the script more easier and faster?
index1= strcmp(a(:,1), 'mama') & strcmp(a(:,3), '1');
val1 = unique(index1);
val_unica1 = nnz(val1);
index2= strcmp(a(:,1), 'mama') & strcmp(a(:,3), '2');
val2 = unique(index2);
val_unica2 = nnz(val2);
index3= strcmp(a(:,1), 'mama') & strcmp(a(:,3), '3');
val3 = unique(index3);
val_unica3 = nnz(val3);
total= sum(val_unica1) + sum(val_unica2) + sum(val_unica3);
  2 件のコメント
Stephen23
Stephen23 2022 年 6 月 1 日
編集済み: Stephen23 2022 年 6 月 1 日
Very interesting code. Because STRCMP returns a boolean array:
index1= strcmp(a(:,1), 'mama') & strcmp(a(:,3), '1');
this line:
val1 = unique(index1);
will return one of [], FALSE, TRUE, or [FALSE,TRUE]. You then count how many times TRUE occurs:
val_unica1 = nnz(val1);
which will return either 0 or 1. It would be simpler and more efficient to use ANY.
Cristian Martin
Cristian Martin 2022 年 6 月 1 日
編集済み: Cristian Martin 2022 年 6 月 1 日
Yes, because I want for the below matrix to set an edit text for counting a sum of unique entry for mama 1, mama2, mama3 and so on
a = {'mama', '5', '1';
'mama', '4', '1';
'mama', '6', '1';
'mama', '7', '2';
'mama', '7', '2';
'mama', '7', '1';
'mama', '7', '3';
'mama', '7', '3';
'mama', '8', '1'};
disp(total);
3

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

採用された回答

Steven Lord
Steven Lord 2022 年 6 月 1 日
a = {'mama', '5', '1';
'mama', '4', '1';
'mama', '6', '1';
'mama', '7', '2';
'mama', '7', '2';
'mama', '7', '1';
'mama', '7', '3';
'mama', '7', '3';
'mama', '8', '1'};
rowsWithMama = strcmp(a(:, 1), 'mama')
rowsWithMama = 9×1 logical array
1 1 1 1 1 1 1 1 1
rowsWith1 = strcmp(a(:, 3), '1')
rowsWith1 = 9×1 logical array
1 1 1 0 0 1 0 0 1
nnz(rowsWithMama & rowsWith1)
ans = 5
If you have multiple values you want to test for in column 3 consider using ismember.
rowsWith2Or3 = ismember(a(:, 3), {'2', '3'})
rowsWith2Or3 = 9×1 logical array
0 0 0 1 1 0 1 1 0
or, using string to make creation of the list of search terms easier by avoiding needing to manually create '2', '3', '4', ... '50':
s = string(2:3)
s = 1×2 string array
"2" "3"
rowsWith2Or3 = ismember(a(:, 3), s)
rowsWith2Or3 = 9×1 logical array
0 0 0 1 1 0 1 1 0
  1 件のコメント
Cristian Martin
Cristian Martin 2022 年 6 月 1 日
Thank you for the valuable information!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by