0
votes

I have just started learning MATLAB . Please find my codes below

m= ['A','B','C'];
cs=size(m,2);
for i=1:cs
    for j=1:cs

            if i~=j
             s1=(m(i));s2=',';s3=(m(j));
                 s=strcat(s1,s2,s3);
                     disp(s);
        end    
    end
end

It produces the following output on command window.

A,B
A,C
B,A
B,C
C,A
C,B

But , i want to wrap up all the outputs into a single matrix (or Cell Array ) , Lets say new_M . So that the values of new_M shall contain the all above values like this .

new_M (6,1) =
[ A,B 
A,C
B,A
B,C
C,A
C,B ] 

Your help will be highly appreciatated . Thanks in advance.

3

3 Answers

1
votes

The idiomatic way to do this would be to use nchoosek to get the indices you want and then use linear indexing:

m = ['A','B','C'] %// For a char array OR
m = {'A','B','C'} %// For a cell array
I = nchoosek(1:numel(m), 2)
new_M = m([I; I(:,end:-1:1)])
1
votes

This will work. In 'c' you will find the values

    m= ['A','B','C'];
cs=size(m,2);
c = cell(6,1)
t = 1;
for i=1:cs
    for j=1:cs

            if i~=j
             s1=(m(i));s2=',';s3=(m(j));
                 s=strcat(s1,s2,s3);
                 disp(s)
                 c{t} = s;
                 t=t+1;
        end    
    end
end
1
votes
m= ['A','B','C'];
cs=size(m,2);
new_M = [];
for i=1:cs
    for j=1:cs
        if i~=j
         s1=(m(i));s2=',';s3=(m(j));
         s=strcat(s1,s2,s3);
         new_M = [new_M;s];
        end    
   end
end

The new_M matrix will contain all the values you need.