Search code examples
arraysmatlabcell-array

Return values in cell array based on a condition


I have a 1x3 cell array that looks like this:

str = strings(6,1)
str(1) = 'A'
str(2) = 'B'
str(3) = 'A'
str(4) = 'B'
str(5) = 'A'
str(6) = 'B'

str2 = strings(6,1)
str(1) = 'r'
str(2) = 'r'
str(3) = 't'
str(4) = 's'
str(5) = 't'
str(6) = 'm'

a = [345; 344; 234; 234; 235; 231]

CA{1} = str
CA{2} = str2
CA{3} = a

I need to extract the values in column 3 where: column 1 shows an 'A' AND column 2 shows a 't'.

I cannot even find a start on how to approach it, hope someone can help me! I have tried the codes below, but they return an empty vector, that is probably due to my misspecification of the problem, sorry for that!!


Solution

  • I always use the KISS code (Keep it simple stupid). The method I'm proposing may not be the fastest or the most elegant, but I tried it and it works.

    % I'm using the length of cellarray{1} as reference, since all cells are the same length
    for k = 1:length(cellarray{1})
        if ((cellarray{1}(k) == 'A') && (cellarray{2}(k) == 't'))
            % Assign the value to a new vector, or display the value... But this is how you get to it.
            disp(cellarray{3}(k));
        end
    end
    

    I called your cell array cellarray in this example. You could also use strcmp instead of ==, in fact you will need to if ever you're comparing more than just one character.