Replacing the values in a column of a matrix

8 views (last 30 days)
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.

Accepted Answer

Murugan C
Murugan C on 6 Sep 2021
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);

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!