how do I index a vector with another vector without the use of a for loop

3 ビュー (過去 30 日間)
Samuel Morstein
Samuel Morstein 2020 年 2 月 3 日
編集済み: Stephen23 2020 年 2 月 3 日
For my matlab homework, given a character vector of 1x(6N) and a logical vector of 1xN, I have to make a function that returns a 1xP vector of the characters that corrrespond to the false values of the logical vector and a 1xM vector of the roginial positions of the characters that correspond to the true values of the logical vector.
Example:
events = 'TRACK ​CYCLI ​SWIMM ​BOXIN ​DIVIN FENCI '
belong = [true​ ​false​ ​true​ ​false​ ​true​ ​true]
[wrong, positions] = eventList(events, belong)
wrong → 'CYCLI BOXIN '
positions → [​1​ ​3​ ​5​ ​6​]
I am able to do everything but return the characters in wrong beyond the first six characters. Here is my code:
function [wrong,positions] = eventList(events,belong)
positions=find(belong==true)
y=1:6:length(events)
z=y(find(belong==false))
len(1:length(events))=true
len(z:z+5)=false
wrong=events(find(len==false))
end
I'm not sure how to change line six so that it uses every value in z instead of only the first value without the use of a for loop.

回答 (1 件)

Stephen23
Stephen23 2020 年 2 月 3 日
編集済み: Stephen23 2020 年 2 月 3 日
>> idx = ~reshape(repmat(belong,6,1),1,[]); % or use REPELEM.
>> events(idx)
ans = CYCLI BOXIN
>> find(belong)
ans =
1 3 5 6

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by