Why changing a specific element in a vector matrix makes the unchanged elements zero?!

I have the following code, where there are two rows, the first one has a set of values, the second one is a sorted version of it. Now, if there are multiple equal values in the first row, I want to change all of these values except the first one by adding a random number to these values in the first row and their corresponding values in the second row. The problem is that if a repetition happens and the program adds these random numbers, it changes all the unique values to zero.
Any help is appreciated. Thank you very much.
if true
clc
clear all
close all
c=4;
ObFunVal =1.0e-11*[0.8582 0.8582 0.8582 0.9163];
ObFunVal_Ascending =1.0e-11*[0.8582 0.8582 0.8582 0.9163];
for j=1:c
ch=find(ObFunVal==ObFunVal_Ascending(c-j+1));
ch_Length=numel(ch);
if(ch_Length>1)
for i=2:ch_Length
RandomNum=rand;
ObFunVal(ch(i))=ObFunVal(ch(i))+RandomNum;
ObFunVal_Ascending(c-j+2-i)=ObFunVal_Ascending(c-j+2-i)+RandomNum;
end
end
end
ObFunVal
ObFunVal_Ascending
end

 Respuesta aceptada

It doesn't change the values to 0. You are adding values with rand without considering the magnitude of the rest of the values in the vector. You can easily see this if you display ObFunVal(1). RandomNum=rand*1.0e-12; would solve your issue.

5 comentarios

Yes, you're right. Thank you very much.
It does seem a very complicated method for something that can also be done without several loops:
ObFunVal =1.0e-11*[0.8582 0.8582 0.8582 0.9163];
ObFunVal_Ascending =1.0e-11*[0.8582 0.8582 0.8582 0.9163];
[~,b]=ismember(ObFunVal,unique(ObFunVal));
IsRepeat=[false ~diff(b)];
rand_vector=rand(1,sum(IsRepeat))*1.0e-12;
rand_vector_sorted=sort(rand_vector);
ObFunVal(IsRepeat)=ObFunVal(IsRepeat)+rand_vector;
%or:
%ObFunVal(IsRepeat)=ObFunVal(IsRepeat)+rand_vector_sorted;
ObFunVal_Ascending(IsRepeat)=ObFunVal_Ascending(IsRepeat)+rand_vector_sorted;
clc
ObFunVal
ObFunVal_Ascending
Thank you Rik so much. The problem with me is that I don't know how to become familiar with such specialized Matlab functions, that's why I sometimes use general programming! I appreciate it if you could give some tips.
Okay, thank you, Rik, so much.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Preguntada:

el 11 de Oct. de 2018

Comentada:

el 12 de Oct. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by