use two indexes at the same time in a for loop
Show older comments
Hi! I have the following matrix:
M = [26 45 15 47 78 9 6 45 14 66 95 6;
65 35 96 39 7 88 47 11 14 75 77 86;
41 25 37 84 92 66 96 67 44 21 33 49;
52 65 95 85 74 37 12 45 55 17 99 47;
82 99 32 41 55 47 33 28 47 87 96 25];
I need to replace some numbers in the bottom left-hand corner with the numbers in the following matrix:
matrix_left = [0 0; 0 0];
The output matrix must be this:
M = [26 45 15 47 78 9 6 45 14 66 95 6;
65 35 96 39 7 88 47 11 14 75 77 86;
41 25 37 84 92 66 96 67 44 21 33 49;
0 0 95 85 74 37 12 45 55 17 99 47;
0 0 32 41 55 47 33 28 47 87 96 25];
I tried the following code, but I can't understand how to use the "i" and "k" values at the same time.
M = [26 45 15 47 78 9 6 45 14 66 95 6;
65 35 96 39 7 88 47 11 14 75 77 86;
41 25 37 84 92 66 96 67 44 21 33 49;
52 65 95 85 74 37 12 45 55 17 99 47;
82 99 32 41 55 47 33 28 47 87 96 25];
matrix_left = [0 0; 0 0];
for i = 4:5 & k = 1:2
for j = 1:2
M(i,j) = matrix_left(k,j);
end
end
Accepted Answer
More Answers (1)
for i = 4:5 & k = 1:2
This is pure guessing. While some human can understand, what you want, if you apply such trivks inspoken language, formal systems like programming languages do not tolerate it.
A simple solution is to omit the loop:
M(4:5, 1:2) = matrix_left;
If you really want a loop or this was a simplified example only, you can use "2nd-level indexing":
index_M1 = 4:5;
index_M2 = 1:2;
index_L1 = 1:2;
index_L2 = 1:2;
for i1 = 1:numel(index_M1)
for i2 = 1:numel(index_M2)
M(index_M1(i1), index_M2(i2)) = L(index_L1(i1), index_L2(i2));
end
end
This is a usual method, if the argument is not an integer:
t = 0:0.01:pi;
x = zeros(size(t));
for k = 1:numel(t)
x(k) = sin(t(k));
end
x(t) would not work, but this kind of indexing combines x(k) with t(k).
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!