How to fill a zeros matrix with text?

12 次查看(过去 30 天)
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

回答(2 个)

Star Strider
Star Strider 2019-2-4
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 2019-2-4
编辑:Kevin Phung 2019-2-4
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'};

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by