How to index two vectors together
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2023-11-24
"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{:}]
Dyuman Joshi
2023-11-24
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
tic
C = arrayfun(@colon,vec_A,vec_B,'uni',0);
toc
采纳的回答
Dyuman Joshi
2023-11-24
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
out1 = [out1{:}]
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
out2 = [out2{:}]
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.
0 个评论
更多回答(1 个)
Bruno Luong
2023-11-24
编辑:Bruno Luong
2023-11-24
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!