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

Antworten (1)

John D'Errico
John D'Errico am 7 Okt. 2017

0 Stimmen

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 Kommentar

The problem is how do I assign a value to c(x, y, z) which is b(ind) untill c is filled.
I can't do something like that
coords = [randi(bw, ah * aw, 1), randi(bh, aw * ah, 1)];
coords = sub2ind(size(b), coords(:, 1)', coords(:, 2)');
c(:, :, :) = b(coords(:));

Melden Sie sich an, um zu kommentieren.

Kategorien

Gefragt:

am 7 Okt. 2017

Kommentiert:

am 7 Okt. 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by