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