How to fill a zeros matrix with text?
2 ビュー (過去 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!