0

I am working in Matlab. I created a matrix and then a cell array based on that matrix: A = randi([1 5], 5, 5); B = num2cell(A);

I want to replace the numbers in B with different strings based on A's columns.

For example, where column
A(:,1) == 1 replace with 'Cat' and A(:,2) == 1 replace with 'Dog'

If A = [ 1 2 1 3 5; 2 1 5 1 4; 1 1 2 5 1; 5 5 3 4 1; 1 1 2 5 2]

Then I want B = [ Cat 2 1 3 5; 2 Dog 5 1 4; Cat Dog 2 5 1; 5 5 3 4 1; Cat Dog 2 5 2]

I have tried B(A(:, 1) == 1) = {'Cat'} and B(A(:,2) == 1) = {'Dog'} but everything keeps getting placed in B's first column. I can't figure out the indexing.

Appreciate the help!

4
  • 1
    You need to add an index for the column in the cell array. Commented Sep 23, 2021 at 15:12
  • How? I have tried several ways and keep getting errors. Commented Sep 23, 2021 at 15:20
  • 1
    B(A(:,1) == 1, 1) = {'Cat'} should work. Or even B(A(:,1) == 1, 1) = 'Cat' Commented Sep 23, 2021 at 16:28
  • Thank you, B(A(:,1) == 1, 1) = {'Cat'} and B(A(:,2) == 1, 2) = {'Dog'} did the trick! Commented Sep 23, 2021 at 17:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.