开发者

array operation in matlab

开发者 https://www.devze.com 2023-04-04 22:47 出处:网络
I am a newbie at MATLAB and apologies if this question is already repeated. I have a matrix, where each row is a vector. I am trying to normalise each vector into a unit.

I am a newbie at MATLAB and apologies if this question is already repeated.

I have a matrix, where each row is a vector. I am trying to normalise each vector into a unit. I have tried the following

   vector_b=zeros(1,1);
    normVector_b=zeros(1,1);
     for i=1:3
       b=a(i,:);
         vector_b=[vector_b,b];
           norm_b=b/norm(b);
            normVector_b=[normVector_b,norm_b];
          end

I am able to extract each row vector and normalise it but I have to intilise the vector_b and normVector_b to some values without which I get a pre allocation error. But if I initailize this the first element in the result is

0    0.2673    0.5345    0.8018    0.4558    0.56开发者_开发百科98    0.6838    0.5026    0.5744    0.6462

I am wondering if there is any way I can get rid of the first 0 ?

Thanks, Bhavya


Try this:

vector_b=[];
normVector_b=[];
...


I am not sure what the issue is with pre allocation, because strictly speaking, matlab doesn't require it for matrices. The leading zero you put in yourself in vector_b=[vector_b,b]; where vector_b is initially a zero. Same goes for normVector_b

Anyway, this should work:

% test matrix
test = [1 2 3 4; 5 6 7 8 ; 9 10 11 12];

%  reserve space for result
res = zeros(size(test));

%  loop over rows
for i = 1:1:size(test, 1)
    res(i, :) = test(i, :)./sqrt(sum(test(i, :).^2));
end


Here is a vectorized solution:

%# some random matrix
a = random(10,4);

%# b(i,:) = a(i,:) ./ norm(a(i,:))
b = bsxfun(@rdivide, a, sqrt(sum(a.^2,2)))
0

精彩评论

暂无评论...
验证码 换一张
取 消