필터 지우기
필터 지우기

how to automate this manual code containing if else conditons?

조회 수: 2 (최근 30일)
taimour sadiq
taimour sadiq 2024년 2월 15일
편집: Les Beckham 2024년 2월 15일
i m creating a data based on values in variable seletion... if first value of selection is 1 it will pick data from Values cell 1 else if if contains 2 then from values cell 2... it works fine in this case but my data may change every time suppose now Selection = [1 1 1 2 2 2 3 3 3 3] and there are there sets of values or next time may b more or less.. how can i automate my code.. kindly guide..

채택된 답변

Stephen23
Stephen23 2024년 2월 15일
S = [1 1 1 1 2 2 2 2 2 2];
V{1} = [20 10 40 50 40 30 20 10 20 30];
V{2} = [10 20 30 20 10 30 20 40 20 30];
M = vertcat(V{:});
Z = M(sub2ind(size(M),S,1:numel(S)))
Z = 1×10
20 10 40 50 10 30 20 40 20 30

추가 답변 (1개)

Les Beckham
Les Beckham 2024년 2월 15일
편집: Les Beckham 2024년 2월 15일
Here is one approach. I eliminated the extraneous parameter ini for this example.
I'm not sure I understand the role of the Time vector here. This may not do what you want if the sizes of Time and Selection are not the same.
Time = 1:10;
Selection = [1 1 1 1 2 2 2 2 2 2];
Values{1} = [20 10 40 50 40 30 20 10 20 30];
Values{2} = [10 20 30 20 10 30 20 40 20 30];
Final = zeros(size(Time));
uniqueValues = unique(Selection);
for ii = 1:numel(uniqueValues) %<<< handles any number of unique values in Selection
Final(Selection == uniqueValues(ii)) = Values{ii}(Selection == uniqueValues(ii));
end
disp(Final)
20 10 40 50 10 30 20 40 20 30
  댓글 수: 2
taimour sadiq
taimour sadiq 2024년 2월 15일
your Code is fine just one numeric mistake that why i was not getting the desired result.. now its works fine.. Thanks
Final(Selection == uniqueValues(ii)) = Values{1}(Selection == uniqueValues(ii));
should be
Final(Selection == uniqueValues(ii)) = Values{ii}(Selection == uniqueValues(ii));
Les Beckham
Les Beckham 2024년 2월 15일
You are quite welcome. Good catch on that indexing error. I'll fix the answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by