Search code examples
matlabstrcmpcell-array

matlab code that previously worked using strcmp to pull values associated with strings out of a cell array now does not work


This is an old code I have used before but I simply modified it for a new set of data. I keep getting the error at the bottom though and I have no idea why. Any help would be greatly appreciated!! I put the entire code below.

sites = importdata('genes_with_mir148_sites.txt');

Data = importdata('gene_exp_LFC_table.txt');
names = Data.textdata
LFC = Data.data

C = intersect(names, sites)

LFCcell = {names, LFC}
L = zeros(length(C),1);
for i1=1:length(C)
L(i1)=LFC(strcmp(C(i1),names));
end

Sites = {C,L}

And I get the error: In an assignment A(I) = B, the number of elements in B and I must be the same.


Solution

  • As per our comments discussion, the core reason is this statement:

    L(i1)=LFC(strcmp(C(i1),names));
    

    The amount of elements you are trying to assign on the left side of your expression do not equal the right side of your expression.

    Given the links to your text files in your comments, this occurs at i1 = 23, with the name 2810417H13Rik in the sites cell array. When trying to find a match in names, there are two matches. These are found at indices 12649 and 13043. When pulling the numerical data at these locations, you are in fact producing a 2 x 1 array. As such L(i1) is expecting a single element when you are actually trying to assign a 2 x 1 array to this element.

    As such, I have two recommendations for you to avoid this error:

    1. Is every name in gene_exp_LFC_table supposed to be unique? If it is, then you need to remove one of these rows for your current code to work.

    2. Change L to be a cell array to allow for uneven assignment of values per cell. This will allow you to have multiple matches per name should this be encountered.