How to fill specific elements of vector based on indexes of another vector?
6 views (last 30 days)
Show older comments
Hi all!
i have a problem and i want to share with you in order to get some help.
i have two vectors d1 , d2 with same dimension as shown :
d1=[10 0 0 0 0
0 11 0 0 0
0 0 0 20 0
0 0 0 0 21]
d2=[10 0 0 0 0
0 15 0 0 0
0 0 0 20 0
0 0 0 0 12]
i did a comparison between each elements in both d1 and d1 as follow :
if d1<d2, keep value in d1 and put "0" in d2
if d1>d2, keep value in d2 and put "0" in d1
if d1=d2 , i add 100 to both value and keep them in same matrices.(i did this in order to distinguish the needed value later because it may exist other same values in my real matrix).
the result as shown :
d1=[110 0 0 0 0
0 11 0 0 0
0 0 0 120 0
0 0 0 0 0]
d2=[110 0 0 0 0
0 0 0 0 0
0 0 0 120 0
0 0 0 0 12]
i put the result with an order in two vectors V1 and V2 as following( here they have same dimension but usually with different dimension :
V1=[110 V2=[110
11 120
120] 12]
after this i will focus only for value >100 . so i extracted their indexes
I1=[1 I2=[1
3] 2]
I have taken into account another condition, G1 and G2 containing values corresponding to V1 and V2 successively.
G1=[3 G2=[3
5 6
3] 4]
Now , i will compare just the extracted elements :
for i=1:size(I1,1)
if G1(I1(i))>G2(I2(i))
V1(I1(i)=0
V2(I2(i))=V2(I2(i))-100 %return the intial value
elseif G1(I1(i))=<G2(I2(i))
V1(I1(i)=V1(I1(i)-100
V2(I2(i))=0
end
end
the result is the following :
V1=[10 V2=[0
11 0
20] 12]
after this i will remove zero rows.
the final result:
V1=[10 V2=[12]
11
20]
I did all this but i can't acheive the required result.
i hope that you could help me.
4 Comments
Answers (1)
Image Analyst
on 29 Oct 2022
Please format your code and paragraphs better. It's difficult to read. This is as far as I got:
d1=[10 0 0 0 0 0 11 0 0 0 0 0 0 20 0 0 0 0 0 21];
d2=[10 0 0 0 0 0 15 0 0 0 0 0 0 20 0 0 0 0 0 12];
% Not sure what this means: V1=[110 V2=[110 11 120 120] 12]
% Not sure what this means I1=[1 I2=[1 3] 2]
% "if d1<d2, keep value in d1 and put "0" in d2 if d1>d2,"
mask = d1 > d2;
d2(mask) = 0; % d1 remains untouched -- keeps it's original values.
% "keep value in d2 and put "0" in d1 if d1=d2"
mask = d1 == d2;
d1(mask) = 0 % d2 remains untouched.
% "add 100 to both value and keep them in same matrices." but apparently
% only where there are non-zero values.
mask = d1 == 0;
d1(mask) = d1(mask) + 100;
mask = d2 == 0;
d2(mask) = d2(mask) + 100;
Sorry I can't help you with the rest. The rest of your explanation is an unintelligible run-on sentence where we have no idea what you're saying. Please use spaces, bullet points, separate lines, and code-formatting with the code icon/button to make it readable and understandable.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!