How to fill a zeros matrix with text?

7 views (last 30 days)
Lisa de Boer
Lisa de Boer on 4 Feb 2019
Edited: Kevin Phung on 4 Feb 2019
I have created a matrix filled with zeros and I want to fill this matrix by using a for loop. However, instead of filling it with numbers, I want to fill it with text. When I try to run the code, I get the error: 'unable to perform assignment because of the left side is 1-by-1 and the size of the right side is 1-by-12. Also, not all the text returns are the same size. The first is 1x12, the second 1x13 and the third 1x12. However, I think I can solve this by using extra blanks.
matrix = zeros(12)
for i:12;
for j:12;
if i>j;
matrix(i,j) = 'first option'
elseif i<j
matrix(i,j) = 'second option'
else
matrix(i,j) = 'third option'
end
end
end

Answers (2)

Star Strider
Star Strider on 4 Feb 2019
I am not certain what you are doing. The string (link) variable type (introduced in R2016b), may do what you want.

Kevin Phung
Kevin Phung on 4 Feb 2019
Edited: Kevin Phung on 4 Feb 2019
Your syntax for your for loop is incorrect, I think you mean to say:
for i = 1:12
for j = 1:12
%etc etc
end
end
and also, you cant have strings and numerics in an array -- you're going to need to switch to a cell array/matrix.
anyway, maybe this does what you want without a for loop:
n = 12; %
a = ones(n); %creates nxn matrix
ind = logical(tril(a,-1)); % this is the i<j condition
ind2 = logical(triu(a,1));% i>j condition
ind3 = logical(eye(size(a,1))); % i ==j condition
test_M = cell(n); %this will be your matrix
test_M(ind) = {'first option'};
test_M(ind2) = {'second option'};
test_M(ind3) = {'third option'};

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!