0

I have a cell array of length 3 and I want to make a for loop with another cell array with length of 6 , so how can I add extra 3 cells for the first array in order to make the 2 cell arrays equal and to use my for loop in MATLAB?

For example, with 2 inputs:

type = { '12' '62' '5' };
colour = {'re' 'green' 'yellow' 'brown' 'blue' 'black'};

for i = 1:length(colour)
    if isequal(colour(i), type(:))
        result(i) = type(i);
    else
    end
end

I need to make the type cell array with the same size with colour cell array (I think I have to add extra 3 empty cells in side the type cell array).

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Gloria
  • 329
  • 4
  • 17

1 Answers1

2

I have to address several issues in your code first:

  1. If you use a cell array, you must use curly braces ({}) to extract elements from it. Instead of writing colour(i) you should be writing colour{i}.

  2. This is not a problem, but it's a matter of good practice. If you don't need to handle the else part of the if statement, don't write it at all.

  3. Preallocate memory so that arrays don't grow inside the loop (it slows down the program). Specifically, add the line result = cell(size(colour)); before the for loop.

  4. Your isequal logic is flawed. Practically, it would always return false because colour{1} is one element and type{:} is many.

  5. According to your example, types contain numbers and colours letters, although they are both strings. Does it make sense to compare the two?

Now, regarding your question, it's up to you to decide how the for loop runs. Since you don't mention what you want to achieve (you rather ask how you want to achieve something without saying what exactly), I cannot say what your for loop should look like, if necessary at all. Maybe you meant to use ismember instead of isequal? If so, the fixed code can look like this:

result = cell(size(colour));
for i = 1:length(colour)
    if ismember(colour{i}, type)
        result{i} = type{i};
    end
end

or shorter, like this:

result = cell(size(colour));
[found, idx] = ismember(colour, type);
result(found) = type{idx(found)}

If you provide more details, maybe I can refine my answer so that it helps you more.

Eitan T
  • 32,660
  • 14
  • 72
  • 109