I want to input an array of odd/even mixed numbers like [ 1 2 3] and i want the output to be like [ odd even odd] . Added my code, its showing error, Can you tell me where i

1 回表示 (過去 30 日間)
A=[1 2 3 4;5 6 7 8;9 10 11 12];
p=size(A,1);
q=size(A,2);
S=zeros(3,4);
for i=1:1:p
for j=1:1:q
if mod(A(i,j),2)==0
S(i,j)='even';
else
S(i,j)='odd';
end
end
end

採用された回答

Voss
Voss 2021 年 12 月 2 日
S cannot be a numeric matrix if it's going to contain character arrays. It can be a cell array though:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
[p,q] = size(A);
S = cell(p,q);
for i = 1:p
for j = 1:q
if mod(A(i,j),2) == 0
S{i,j} = 'even';
else
S{i,j} = 'odd';
end
end
end
  2 件のコメント
Voss
Voss 2021 年 12 月 2 日
And here's a better way, using logical indexing:
S = cell(size(A));
is_even = mod(A,2) == 0;
S(is_even) = {'even'};
S(~is_even) = {'odd'};
TM Abir Ahsan
TM Abir Ahsan 2021 年 12 月 2 日
Got it! Thank you so much man!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 12 月 2 日
You can use a string array instead of a double array like you get from zeros():
A=[1 2 3 4;5 6 7 8;9 10 11 12];
[rows, columns] = size(A)
rows = 3
columns = 4
S=repmat("Unknown", [rows, columns]); % Instantiate string array.
for row = 1 : rows
for col = 1 : columns
if mod(A(row,col),2)==0
S(row,col)="even";
else
S(row,col)="odd";
end
end
end
S % Show in command window.
S = 3×4 string array
"odd" "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by