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 visualización (últimos 30 días)
Mostrar comentarios más antiguos
TM Abir Ahsan
el 2 de Dic. de 2021
Comentada: TM Abir Ahsan
el 2 de Dic. de 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 comentarios
Respuesta aceptada
Voss
el 2 de Dic. de 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 comentarios
Voss
el 2 de Dic. de 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'};
Más respuestas (1)
Image Analyst
el 2 de Dic. de 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.
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!