i want the loop to run only one time, it keeps running until it subtract 84 instead of 6
조회 수: 3 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
Jan
2023년 1월 20일
편집: Jan
2023년 1월 20일
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
Jan
2023년 1월 22일
@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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!