Hi. I have question regarding to cell string and matrix. I have matrix F and cell string D. I want to create another cell string Y.
F =
0 0 0 0
1 0 0 1
0 1 1 1
1 1 1 1
D =
'A'
'B'
'C'
'D'
Therefore, I want to create Y with output like this.
Y =
'-'
'A, D'
'B, C, D'
'A, B, C, D'
The steps are:
-1- recognize column positions of value 1 for row 1 in F.
-2- the column positions are equal to row positions of D. So, string in that row positions will input to row 1 of Y.
-3- do the same step for next row in F and D. If no value 1 for that row, that row position of Y will be empty, and maybe can be replace with sign - as to indicate no string available from D.

 채택된 답변

Stephen23
Stephen23 2017년 7월 4일
편집: Stephen23 2017년 7월 4일

1 개 추천

[col,row] = find(F');
fun = @(v){sprintf(', %s',D{v})};
out = accumarray(row,col,[],fun);
out = cellfun(@(s)s(3:end),out,'uni',0)
out(cellfun('isempty',out)) = {'-'};
giving:
>> out{:}
ans = -
ans = A, D
ans = B, C, D
ans = A, B, C, D

댓글 수: 3

fun = @(v) {strjoin(D(v), ', ')};
would be a lot simpler since you then don't need the cellfun to remove that leading ', ' inserted by sprintf:
[col,row] = find(F');
fun = @(v) {strjoin(D(v), ', ')};
out = accumarray(row,col,[],fun);
out(cellfun('isempty',out)) = {'-'};
Stephen23
Stephen23 2017년 7월 4일
편집: Stephen23 2017년 7월 4일
@Guillaume: agreed... but sadly not on the MATLAB version I have.
Guillaume
Guillaume 2017년 7월 4일
편집: Guillaume 2017년 7월 4일
It's trivial to implement:
function s = strjoin(strings, joint)
join = cell(2, numel(strings));
join(1, :) = strings(:);
join(2, 1:end - 1) = {joint};
s = [join{:}];
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KSSV
KSSV 2017년 7월 4일

1 개 추천

F =[0 0 0 0
1 0 0 1
0 1 1 1
1 1 1 1] ;
D = {'A' 'B' 'C' 'D'} ;
F = logical(F) ;
for i = 1:4
iwant = D(F(i,:))
end

댓글 수: 2

Jan
Jan 2017년 7월 4일
편집: Jan 2017년 7월 4일
Note: Changing the type of a variable can degrade the processing speed, because the JIT acceleration is impeded. Something like LF=logical(F) is a very cheap way to increase the speed.
The final iwant is not similar with Y. The output is like this
iwant =
Empty cell array: 1-by-0
iwant =
'A' 'D'
iwant =
'B' 'C' 'D'
iwant =
'A' 'B' 'C' 'D'
so final is ABCD in one row, not 4 rows, unlike Y. Can you help me find the right one?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2017년 7월 4일

편집:

2017년 7월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by