2012-07-23 64 views
1

我將不勝感激您在matlab中的以下問題的幫助: 我有一個向量,我想根據以下兩個向量選擇它的一部分部分的開始和結束索引:基於兩個向量的起點和終點位置選擇一個向量的元素matlab

aa = [1 22 41 64 83 105 127 147 170 190 212 233] 
bb = [21 40 63 82 104 126 146 169 189 211 232 252] 

基本上我想在V(1:21)V(22:40)執行某些功能,... V(233:252)。 我試過V(aa:bb)V(aa(t):bb(t))其中t = 1:12但我只得到V(1:21),可能是因爲V(22:40)有19個元素,而V(1:21)有22個元素。

有沒有快速的編程方式?

+0

你想應用的功能是什麼? – 2012-07-23 10:04:46

回答

1

將選擇在一個單元陣列,並應用功能,每個單元:

aa = [1 22 41 64 83 105 127 147 170 190 212 233] 
bb = [21 40 63 82 104 126 146 169 189 211 232 252] 
V = rand(252,1); % some sample data 

selV = arrayfun(@(t) V(aa(t):bb(t)), 1:12,'uniformoutput',false); 
result = cellfun(@yourfunction,selV) 
% or 
result = cellfun(@(selVi) yourfunction(selVi), selV); 

如果你想申請的功能有標量輸出到每一個向量輸入,這應該給你一個1×12陣列。如果函數給出了向量輸出,你必須包括uniformoutput參數:

result = cellfun(@(selVi) yourfunction(selVi), selV,'uniformoutput',false); 

它給你一個1×12單元陣列。

+0

非常感謝。 – user1545441 2012-07-23 10:15:55

0

如果你想在一個高度濃縮的形式運行它,你可以寫(在兩行,爲清楚起見)

aa = [1 22 41 64 83 105 127 147 170 190 212 233] 
bb = [21 40 63 82 104 126 146 169 189 211 232 252] 
V = rand(252,1); % some sample data borrowed from @Gunther 

%# create an anonymous function that accepts start/end of range as input 
myFunctionHandle = @(low,high)someFunction(V(low:high)); 

%# calculate result 
%# if "someFunction" returns a scalar, you can drop the 'Uni',false part 
%# from arrayfun 
result = arrayfun(myFunctionHandle(low,high),aa,bb,'uni',false) 

注意,這可能會在這段時間,外在的循環運行速度比較慢,但在未來的版本中,arrayfun可能是多線程的。

相關問題