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

1 view (last 30 days)
batool swaeer on 20 Jan 2023
Commented: Jan on 22 Jan 2023
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

Jan on 20 Jan 2023
Edited: Jan on 20 Jan 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 CommentsShowHide 1 older comment
Jan on 22 Jan 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.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!