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

추가 답변 (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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by