If I want to make an Nx7 array which every odd number, going from left to right has the value of 30 and every even number, going from left to right has a value of 45, how would I do this using for loops?

Réponses (1)

Voss
Voss le 13 Fév 2022

0 votes

Do you mean like this row vector:
[30 45 30 45 30 45 30]
ans = 1×7
30 45 30 45 30 45 30
repeated N times going down? Something like that?
If so, you could loop over the rows of the matrix you want to make:
N = 10;
M = zeros(N,7);
for ii = 1:N
M(ii,:) = [30 45 30 45 30 45 30];
end
disp(M);
30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30
Or you can loop over the columns:
N = 10;
M = zeros(N,7);
for ii = 1:7
if mod(ii,2) == 1
M(:,ii) = 30;
else
M(:,ii) = 45;
end
end
disp(M);
30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30
Or you can double-loop through the elements:
N = 10;
M = zeros(N,7);
for ii = 1:N
for jj = 1:7
if mod(jj,2) == 1
M(ii,jj) = 30;
else
M(ii,jj) = 45;
end
end
end
disp(M);
30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30
Of course you do not need to use any loops at all:
N = 10;
M = repmat([30 45 30 45 30 45 30],N,1);
disp(M);
30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30 30 45 30 45 30 45 30
Or maybe you mean something a little different:
N = 10;
M = zeros(7,N);
for ii = 1:N*7
if mod(ii,2) == 1
M(ii) = 30;
else
M(ii) = 45;
end
end
M = M.';
disp(M);
30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45 30 45

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Question posée :

le 13 Fév 2022

Réponse apportée :

le 13 Fév 2022

Community Treasure Hunt

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

Start Hunting!

Translated by