i want the loop to run only one time, it keeps running until it subtract 84 instead of 6

1 visualización (últimos 30 días)
clc, close all, clear all
A=[75 144 114 102 108; 90 126 102 84 126; 96 114 75 105 135; 105 90 150 90 75; 90 75 135 75 90; 105 60 165 45 120; 115 85 160 100 145];
num_rows= length(A)
num_columns= width(A)
for i=1:num_rows
for j=1:num_columns
if A(:,4)
A(:,4) = A(:,4) - 6
end
end
end

Respuestas (1)

Jan
Jan el 20 de En. de 2023
Editada: Jan el 20 de En. de 2023
Remember that length(A) replies the longest dimension. Maybe you meant height(A). Even if this replies the same value for the example data, avoid length, because it can fail easily.
if A(:,4) might not do, what you expect. The if command requires a scalar condition. A(:,4) is a vector. Therefore Matlab inserts an all() implicitly. Is this wanted?
You run a loop over rows and columns of A, but process A(:,4) only. The body of the loops does not depend on i or j, so what is the purpose of the loops? Most of all, if you want to run the loop once only - isn't it the direct way to omit the loop?
  2 comentarios
batool swaeer
batool swaeer el 20 de En. de 2023
You run a loop over rows and columns of A, but process A(:,4) only. The body of the loops does not depend on i or j, so what is the purpose of the loops?
I know I could solve this issue by just creating another matrix (zeros and 6) and subtracting it from the ooriginal matrix. However, my instroctur wants it to be a loop.
and changing it to Length still gave the same outcome.
Jan
Jan el 22 de En. de 2023
@batool swaeer: I do not understand, what "creating another matrix (zeros and 6)" means. What does "it" mean in "changing it to Length"?
Did you get the core of my answer?
for i=1:num_rows % Loop over rows
for j=1:num_columns % Loop over columns
if A(:,4) % \
A(:,4) = A(:,4) - 6 % | does not depend on i or j
end % /
end
end
A shorter version of this code:
A(:, 4) = A(:, 4) - 6 * (num_rows * num_cols)
It is still not clear what "run the loop only one time" means. This is a contradiction to the nature of loops.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by