Combining text with non-zero elements of a 2D array
2 ビュー (過去 30 日間)
古いコメントを表示
I have a numerical array that is "almost" diagonal, so it looks like this:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
I also have a cell array with the same number of rows, which looks like this:
C={'ABC';'DEF';'GHI';'JKL';'MNO'}
I would like to create a row array that takes the non-zero values of N, and combines them with the text in C to give an output like this:
CN={'ABC10_GHI10' 'DEF20' 'GHI10' 'JKL10' 'MNO30'}
In other words, it must combine all the non-zero values of each column with text of respective indices.
0 件のコメント
採用された回答
Stephen23
2024 年 9 月 16 日
Without an intermediate matrix:
N = [10,0,0,0,0;,0,20,0,0,0;,10,0,20,0,0;,0,0,0,10,0;,0,0,0,0,30]
C = {'ABC';'DEF';'GHI';'JKL';'MNO'}
[X,Y,V] = find(N);
F = @(x)cellstr(join(""+C(X(x))+V(x),'_'));
Z = 1:numel(X);
CN = accumarray(Y,Z(:),[],F)
その他の回答 (2 件)
Voss
2024 年 9 月 16 日
編集済み: Voss
2024 年 9 月 16 日
Here's one way:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
C={'ABC';'DEF';'GHI';'JKL';'MNO'}
n_col = size(N,2);
tmp = compose('%s%d',string(C),N)
CN = cell(1,n_col);
idx = N ~= 0;
for ii = 1:n_col
CN{ii} = strjoin(tmp(idx(:,ii),ii),'_');
end
disp(CN)
0 件のコメント
Voss
2024 年 9 月 16 日
編集済み: Voss
2024 年 9 月 16 日
Here's one way:
N=[10 0 0 0 0; 0 20 0 0 0; 10 0 20 0 0; 0 0 0 10 0; 0 0 0 0 30]
C={'ABC';'DEF';'GHI';'JKL';'MNO'}
n_col = size(N,2);
tmp = compose("%s%d",string(C),N)
CN = strings(1,n_col);
idx = N ~= 0;
for ii = 1:n_col
CN(ii) = join(tmp(idx(:,ii),ii),'_');
end
disp(CN)
CN = cellstr(CN)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!