Replacing the values in a column of a matrix

조회 수: 7 (최근 30일)
Danish Nasir
Danish Nasir 2021년 9월 4일
답변: Murugan C 2021년 9월 6일
Suppose i have a column matrix A=[ 8 8 8 8 17 17 28 26 7 7 7 ]' and a matrix B = [25 21 28 26 16]'
I want to modify matrix A such that,
if "value in A less than value of B and value of A repeats ,
then "the last repeated element should be cahanged such that sum of repeated element should be equal to the element of B"
elseif "value of A equal to element of B"
then "element of A remains unchanged".
E.g. In above case the first element in A is 8 wich is less than first element of B and repeats 4 times
hence the 4th element should be 1 i.e. that is sum of 8+8+8+1=25.
Similarly the 5th element of A is less than 2nd element of B and 5th element repeats 2 times hence 6th element will be 4 i.e. 17+4=21.
Since 7th and 8th elements of A are equal to 3rd and 4th element, hence no change.
The final matrix will be A= [8 8 8 1 17 4 28 26 7 7 2]'
Note:It is given that element value of A is always less than or equal to element value of B
Pls suggest the code.

채택된 답변

Murugan C
Murugan C 2021년 9월 6일
A=[ 8 8 8 8 17 17 28 26 7 7 7 ]' ;
B = [25 21 28 26 16]';
j = 1;
z = 1;
check1 = 0;
result1 = [];
for i = 1 : length(A)
check1 = check1 + A(i);
if B(j) <= check1
sei = B(j) - sum(re_set) ;
re_set(z) = sei;
result1 = [result1 re_set];
re_set = [];
check1 = 0;
z = 1;
j = j + 1;
else
re_set(z) = A(i);
z = z +1;
end
end
disp(result1);

추가 답변 (0개)

카테고리

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

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by