How to Find a Cell in Matlab

Save

Stop tearing your hair out trying to find a cell in Matlab. The Matlab "find" function does not work on cell arrays, nor does logical indexing. Instead, you can use a "for" loop to look through the cell array, one cell at a time. Check each cell with an "if" statement or two to see if it's the one you're looking for. Now you can find the data you need in a Matlab cell array.

  • Construct a standard "for" loop. The counter will run from 1 to the number of elements in your cell array. For example, if C is your two-dimensional cell array, the number of elements in C is equal to the number of rows multiplied by the number of columns. Use the "Size" function to get the number of elements. Your "for" loop might look like this:

    for n=1:(size(C,1)*size(C,2))

    [body of "for" loop]

    end.

  • Construct an "if" statement, with a logical test that will be true only for the cell or cells you want to find. Place it in the body of the "for" loop so that the test is applied to each element of the cell array.

    Remember, a cell array can contain numerical arrays, logical arrays, strings, structure arrays and other data types. Make sure your logical test does not assume a particular data type, unless you know that your cell array contains only one data type. You may want to add a second "if" statement, specifying the data type you are looking for.

    For example, if you are looking for the string "Yes," first test to see if the cell contains a string. If it does, test to see if the string matches "Yes." The "if" statement in the body of your "for" loop might look like this:

    if strcmp(class(C{n}), 'string')

    if strcmp(C{n}, 'Yes')

    [body of "if" statement]

    end

    end.

  • Place the action you want to take when you have found the cell into the body of your "if" statement. You might want to save the index of that cell so you can refer to it later, save the cell contents in another variable or do something to the cell contents. This part will vary according to your specific needs.

  • Save your Matlab script and run it. You have now found your cell.

Tips & Warnings

  • If your cell array is not named "C," simply replace "C" with the name of your array.
  • If your script doesn't work the first time you run it, use Matlab's "Debug" feature to go through it step by step to locate the error.

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images
Promoted By Zergnet

Comments

Resources

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!