array muddle problem

조회 수: 2 (최근 30일)
darksideofthemoon101
darksideofthemoon101 2011년 4월 7일
Hi,
I have an array composed of pairs of variables,
X=[a1 a2 b1 b2 c1 c2..]
and I want to modify each PAIR by a small random percentage. My percentage modifier is
percent=linspace(0.95,1.05,100);
rand_percent=randperm(length(percent));
modifier=percent(rand_percent(1:length(X)));
Since 'modifier' is the same length as 'X', if I multiply them together I modify every element of 'X'. However, I need to modify each PAIR by the same percentage, ie
X=[0.99a1 0.99a2 1.02b1 1.02b2 0.95c1 0.95c2..]
I'm getting lost in the arrays on this one, any suggestions?

채택된 답변

Laura Proctor
Laura Proctor 2011년 4월 7일
Here's a method that works for what you want to do. If X is length n x 1, create the modifier such that it is only n/2 x 1. Then, multiply the modifier by [ 1 1 ] a 1 x 2 array. This results in an n/2 x 2 array. Then, reshape the transpose to create an n x 1 array which will have each element repeated once. Here's the code:
modifier = percent(rand_percent(1:length(X)/2));
modifier = modifier * [ 1 1 ];
modifier = reshape(modifier',[],1);
Then, the final result can be multiplied element-wise by X:
Y = X.*modifier;

추가 답변 (1개)

Paulo Silva
Paulo Silva 2011년 4월 7일
Laura was faster than me and her code is simple, here's my version
X=[1 2 3 4 5 6]; %just modify X, the code should handle more pairs
lhX=length(X)/2;
percent=linspace(0.95,1.05,lhX);
rand_percent=randperm(length(percent));
modifier=percent(rand_percent(1:lhX));
modifier1=repmat(modifier,2,1); %copy modifier to another line
XX=reshape(X,2,lhX); %put pairs in the same column
XXX=modifier1.*XX; %do the calculation
Xnew=reshape(XXX,1,numel(XXX)); %put all in one line
%Xnew %uncoment this line to see the result

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by