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
댓글 수: 0
답변 (2개)
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.
댓글 수: 0
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'};
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!