Tranform for loop into matrix operation
Mostrar comentarios más antiguos
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
Respuestas (1)
John D'Errico
el 7 de Oct. de 2017
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
1 comentario
nclsp
el 7 de Oct. de 2017
Categorías
Más información sobre Introduction to Installation and Licensing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!