Tranform for loop into matrix operation
이전 댓글 표시
Hello,
I'm new to MATLAB and during our Advanced Image Treatment class we have to use MATLAB to implement research papers algorithm. We have to use no for loops which is quite hard for C/C++ programmers. Here is my question, is it possible to translate this kind of for loops into full matrix operations :
c = zeros(aw, ah, ac);
% This the for loop I want to transform
for i=1:aw
for j=1:ah
r_ib = randi(bw, 1);
r_jb = randi(bw, 1);
c(i, j, :) = b(r_ib, r_jb, :);
end
end
% This is what I've tried
coords = [randi(bw, aw * ah, 1), randi(bh, aw * ah, 1)];
c(:, :, :) = b(coords(:, 1), coords(:, 2), :);
What I'm trying to do is to fill a matrix c with values taken from b at random spots. Size of matrix c is aw * ah * 3 and matrix b is bw * bh * 3. Thank you
답변 (1개)
John D'Errico
2017년 10월 7일
The trick is to convert your subscripts into a single index. The function that can do this for you is sub2ind. For example:
M = magic(3)
M =
8 1 6
3 5 7
4 9 2
So we can extract single elements of M using a subscript.
M(2,3)
ans =
7
M(3,1)
ans =
4
But if we have multiple elements in a list, say the elements in positions (1,1), (2,3), (3,1), we need to use sub2ind.
rowsub = [1 2 3];
colsub = [1 3 1];
M(sub2ind(size(M),rowsub,colsub))
ans =
8 7 4
What does sub2ind do? It thinks about the matrix M as if it was a simple vector, so we used reshape on the array to convert it into a vector. So we are just accessing the elements of M in sequence as they are stored in memory.
sub2ind(size(M),rowsub,colsub)
ans =
1 8 3
카테고리
도움말 센터 및 File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!