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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
TM Abir Ahsan
am 2 Dez. 2021
Kommentiert: TM Abir Ahsan
am 2 Dez. 2021
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
0 Kommentare
Akzeptierte Antwort
Voss
am 2 Dez. 2021
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 Kommentare
Voss
am 2 Dez. 2021
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'};
Weitere Antworten (1)
Image Analyst
am 2 Dez. 2021
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)
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.
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!