Arithmetic Operation on Elements of a Vector satisfying a given condition using Logical Indexing
이전 댓글 표시
I have a problem statement where i have to change the elements of a vector depending on some condition
the vector comprises of random number between 4 to 12 i.e. 4,5,6,7,8,9,10,11,12
for eg. the given vector is A = [ 5,6,8,9,7,5,4,12,11,9,10]
now i have to add a scalar to the given vector , which can be either a -ive number or a +ive number
and any element of the resultant vector greater than 12 should be wrap around and any if the element is smaller than 4 then also it should be wrapped around.
for eg. if my input scalar is 3 , then the element 11 in input vector after addition operation will become 15 which is greater than 12
and should be wrapped around and changed to 5 , like shift in a circular manner.
in second case taking the input scalar as -4 to be added to the vector A , the element 6 will become 2 and should be wrapped around and changed to 11
I can solve this using for loop and if else statement , but i am interested in solving this via logical indexing.
any help on that will be greately appreciated.
답변 (1개)
Ameer Hamza
2020년 5월 3일
편집: Ameer Hamza
2020년 5월 3일
For first question
A = [5,6,8,9,7,5,4,12,11,9,10];
scalar = -4;
lb = 4; % lower bound
ub = 12; % upper bound
A_shift = mod((A-lb)+scalar, ub-lb+1)+lb;
Result
>> A
A =
5 6 8 9 7 5 4 12 11 9 10
>> A_shift
A_shift =
10 11 4 5 12 10 9 8 7 5 6
For second question. Correct syntax is
v(v<0) = v(v<0)-3;
댓글 수: 6
ANKUR WADHWA
2020년 5월 4일
편집: ANKUR WADHWA
2020년 5월 4일
Ameer Hamza
2020년 5월 4일
Try this
A = [5,6,8,9,7,5,4,12,11,9,10];
scalar = 4;
lb = 4; % lower bound
ub = 12; % upper bound
A_ = A + scalar;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
A_shift = mod((A-lb)+scalar, ub-lb+1)+lb;
12-4+1=9 is necessary because the mod will keep the value from 0 to 9-1. If you set it to 8 then you will only get digits from 0 to 7.
ANKUR WADHWA
2020년 5월 4일
Ameer Hamza
2020년 5월 4일
Yes. I just added the last line as example. These lines
A_ = A + scalar;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
shows the correct way to write the function shift().
ANKUR WADHWA
2020년 5월 4일
Ameer Hamza
2020년 5월 4일
Also wrap the shifting factor
wrap = shift('1234', 96)
back = shift(wrap, -96)
% the bounds are 32 and 126 in this case
function coded = shift(A, b)
ub = 126;
lb = 32;
b = rem(b, ub-lb);
A_ = A + b;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
coded = char(A_);
end
카테고리
도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!