Problem Using Nested For Loops
57 ビュー (過去 30 日間)
古いコメントを表示
Scott Banks
2024 年 11 月 6 日 15:18
コメント済み: Scott Banks
2024 年 11 月 7 日 11:31
Dear all,
I have the following problem. I want to manipulate the following matrix:
X = [1 2 3 4 5;
6 7 8 9 10;
11 12 13 14 15;
16 17 18 19 20]
From here I want to separate the columns in this matrix and add values to each number. Thus, for example I want to take:
X(:,1)
And add some values to it. I want to do this for all columns. For X(:,2), X(:,3), X(:,4) and X(:,5)
I have tried this using a nested for loop, but it is not correct.
for i = 1:5
for j = 1:4
if j == 1 || j == 3
X(:,i) = X(:,j) - 10
else j == 2 || j == 4
X(:,i) = X(:,j) + 20
end
end
end
So I aiming to get the 1st and 3rd element in each column of the X matrix and subtract 10 from it. Likewise, I am aiming to take the 2nd and 4th elements in the X matrix in each column and add 20 to them.
Thus I should get finally:
X = [-9 -8 -7 -6 -5;
26 27 28 29 30;
1 2 3 4 5;
36 37 38 39 20]
I am actually trying to solve a much bigger set of data, but I have used this example because it falls on the same principle.
I am not very good with nested for loops. So, can someone help please?
Many thanks
1 件のコメント
Stephen23
2024 年 11 月 6 日 16:16
"I am actually trying to solve a much bigger set of data, but I have used this example because it falls on the same principle."
Avoid loops, just add them.
"I am not very good with nested for loops."
Why do you need to use loops?
採用された回答
Shivam Gothi
2024 年 11 月 6 日 15:53
編集済み: Shivam Gothi
2024 年 11 月 6 日 16:01
Upon investigating your code, it seems that there is an error with the expression coded inside the "if-else" decision block. I rectified it and got the following solution, which aligns with your desired solution.
X = [1 2 3 4 5;6 7 8 9 10;11 12 13 14 15;16 17 18 19 20];
for j = 1:5
for i = 1:4
if (i == 1 || i == 3)
X(i,j) = X(i,j) - 10;
elseif (i == 2 || i == 4)
X(i,j) = X(i,j) + 20;
end
end
end
disp(X)
Also, you can do the operation with single for loop also as shown below:
X = [1 2 3 4 5;6 7 8 9 10;11 12 13 14 15;16 17 18 19 20];
for i = 1:4
if (i == 1 || i == 3)
X(i,:) = X(i,:) - 10;
elseif (i == 2 || i == 4)
X(i,:) = X(i,:) + 20;
end
end
disp(X)
I hope it helps !
2 件のコメント
その他の回答 (1 件)
Voss
2024 年 11 月 6 日 15:45
No loops required:
X = [1 2 3 4 5;
6 7 8 9 10;
11 12 13 14 15;
16 17 18 19 20]
V = [-10; 20; -10; 20]
X = X + V
For your actual data set, you'd have to construct the appropriate column vector V. Indexing operations or the repmat or repelem functions may be convenient for that. It's hard to say without knowing what V needs to be for your real data.
e.g.,
V = repmat([-10; 20],size(X,1)/2,1) % assumes X has an even number of rows
or
V = zeros(size(X,1),1);
V(1:2:end) = -10;
V(2:2:end) = 20
参考
カテゴリ
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!