How to index two vectors together

3 vues (au cours des 30 derniers jours)
Guillem
Guillem le 24 Nov 2023
Modifié(e) : Bruno Luong le 24 Nov 2023
Hi!
I'd like to know how i can index two vectors together. By that I mean that, if for example I have the following two vectors:
vec_A = [1 11 21 31];
vec_B = [4 14 24 34];
How can I get the following vector
vec_C = [1:4 11:14 21:24 31:34];
I know I can do it with a for loop, but is there a way just to do it with vectors?
Thank you very much in advance,
Guillem
  2 commentaires
Stephen23
Stephen23 le 24 Nov 2023
"is there a way just to do it with vectors?"
Not really in a general way. But you can certainly hide the loop:
A = [1,11,21,31];
B = [4,14,24,34];
C = arrayfun(@colon,A,B,'uni',0);
C = [C{:}]
C = 1×16
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
Dyuman Joshi
Dyuman Joshi le 24 Nov 2023
I sometimes forget that such functions exist. Using colon seems to be faster.
But, as I mentioned earlier, for loop would be the best method here.
%Bigger data
vec_A = 10.*(1:1e5)+1;
vec_B = vec_A+3;
tic
out1 = arrayfun(@(x, y) x:y, vec_A, vec_B, 'uni', 0);
toc
Elapsed time is 0.212617 seconds.
tic
C = arrayfun(@colon,vec_A,vec_B,'uni',0);
toc
Elapsed time is 0.076981 seconds.

Connectez-vous pour commenter.

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 24 Nov 2023
One way is to use arrayfun() but that is just a for loop in disguise.
%Bigger data
vec_A = 10.*(1:1e5)+1;
vec_B = vec_A+3;
tic
out1 = arrayfun(@(x, y) x:y, vec_A, vec_B, 'uni', 0);
toc
Elapsed time is 0.214490 seconds.
out1 = [out1{:}]
out1 = 1×400000
11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 51 52 53 54 61 62 63 64 71 72 73 74 81 82
This is same as -
n = numel(vec_A);
out2 = cell(1,n);
tic
for k=1:n
out2{k} = vec_A(k):vec_B(k);
end
toc
Elapsed time is 0.037649 seconds.
out2 = [out2{:}]
out2 = 1×400000
11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 51 52 53 54 61 62 63 64 71 72 73 74 81 82
However, you can see that the for loop is approximately 5.5 times faster than the arrayfun. So, performance wise for loop is the best option.

Plus de réponses (1)

Bruno Luong
Bruno Luong le 24 Nov 2023
Modifié(e) : Bruno Luong le 24 Nov 2023
There is FEX, and fast if you have compiler and compile the mex file.
>> A = [1,11,21,31];
>> B = [4,14,24,34];
>> mcolon(A,B)
ans =
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
>> A:B
ans =
1 2 3 4
You can also overload MATLAB colon operator
>> mcolonops on
>> A:B
ans =
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
>> mcolonops off
>> A:B
ans =
1 2 3 4

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by