array muddle problem

1 回表示 (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by