Vectorize 2 nested 'for' loops with 3D matrix indexing

2 views (last 30 days)
Hello,
This is my piece of code:
%Mono is a huge matrix
a = size(mono,1);
b = size(mono,2);
imA = zeros(a,b,4);
imB = zeros(a,b,4);
for i = 1:a
for j = 1:b
[imA(i,j,:),imB(i,j,:)] = encode(mono(i,j)); % encode is my function that accepts a scalar and returns two non-identical 1x4 vectors.
end
end
Is there a way I could vectorize this?
Tried messing around with bsxfun without success.
Cheers!
  3 Comments
seb leaf
seb leaf on 31 Oct 2019
Edited: seb leaf on 31 Oct 2019
I could, but it would considerably change my outputs. How do you envision what the output would look like if my function accepts 1D arrays knowing that the current output is 2 vectors for scalar inputs?
If possible, I'd prefer to keep my encode function as it is, but if I absolutely need to revise my function I'll do it.
Cyrus Tirband
Cyrus Tirband on 31 Oct 2019
I think there's no way around changing your encode function.
Make it accept N x M arrays, and then have it output two NxMx4 matrices, where each 1x1x4 vector corresponds to the scalar inputs at the same indices.
Vectorising this code will have to happen in the encode function, not in this snippet you showed here.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!