Skipping even indices in a for-loop and subsequently avoiding the odd values to appear in the output
13 次查看(过去 30 天)
显示 更早的评论
Through a nested-for-loop for n=1 and m=1,3 i want to acquire a matrix A with elements a1 and a2
m_length = 3;
n_length = 1;
for n=1:1:n_length
for m=1:2:m_length
a1(n,m) = ((n-1)+m);
a2(n,m) = ((n-1)+m);
end
end
A = [a1 a2];
The above would output A as
A = [1,0,3,1,0,3]
It takes into account the even values of m too (and equates them to 0).
But what i require is purely the odd values of m (i.e. m=1,3) in the matrix.
What i would like to see is:
A = [1,3,1,3]
PS: In the original problem, n = 0,1,2,3,4...n_length and m = 1,3,5,7,9...m_length.
I shortened m and n and their total lengths for ease of explaining the problem.
0 个评论
采纳的回答
Dennis
2019-4-15
When you assign a value to A(3,3)=1, Matlab will create a Matrix of the size 3,3 and will fill empty fields with 0.
A(3,3)=1
A =
0 0 0
0 0 0
0 0 1
This is what is happening in your code. One possible solution might be to fix the index of your matrix:
m_length = 3;
n_length = 1;
for n=1:1:n_length
for m=1:2:m_length
a1(n,(m+1)/2) = ((n-1)+m);
a2(n,(m+1)/2) = ((n-1)+m);
end
end
A = [a1 a2];
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!