dimension mismatch in for loop

Hi, all I would like to save the data from RM to RMS. however there is a dimension error within code. To use for loop i would like to put into data from RM matrix to RMS matrix. Do you have any idea how to match dimension and to save the data to RMS matrix. cheers,
%%%%%%%%%%%%%%%%%%%%%%%%%%% test %%%%%%%%%%%%%%%%%%%%%%%%%%
M = rand(332,7);
x= rand(332,1);
y= rand(332,1);
z= rand(332,1);
r = (x.^2 + y.^2 + z.^2).^0.5;
Bx = rand(332,1);
By = rand(332,1);
Bz = rand(332,1);
Bt = ((Bx).^2 + (By).^2 + (Bz).^2).^0.5;
mu = 10^(-7);
rad = pi/180;
nM = NaN(332,5);
RM = NaN(1,4);
RMS = zeros(9999);
for i = 1:332
nBx = (-mu.*(M(i,4)).*(sin(M(i,6).*rad)).*(cos(M(i,7).*rad))./(r.^3) + 3.*mu.*((M(i,4)).*(sin(M(i,6).*rad)).*(cos(M(i,7).*rad)).*x + (M(i,4)).*(sin(M(i,6).*rad)).*(sin(M(i,7).*rad)).*y + (M(i,4)).*(cos(M(i,6).*rad)).*z).*x./(r.^5));
nBy = (-mu.*(M(i,4)).*(sin(M(i,6).*rad)).*(sin(M(i,7).*rad))./(r.^3) + 3.*mu.*((M(i,4)).*(sin(M(i,6).*rad)).*(cos(M(i,7).*rad)).*x + (M(i,4)).*(sin(M(i,6).*rad)).*(sin(M(i,7).*rad)).*y + (M(i,4)).*(cos(M(i,6).*rad)).*z).*y./(r.^5));
nBz = (-mu.*(M(i,4)).*(cos(M(i,6).*rad))./(r.^3) + 3.*mu.*((M(i,4)).*(sin(M(i,6).*rad)).*(cos(M(i,7).*rad)).*x + (M(i,4)).*(sin(M(i,6).*rad)).*(sin(M(i,7).*rad)).*y + (M(i,4)).*(cos(M(i,6).*rad)).*z).*z./(r.^5));
nx = nBx .* 1.0e+9;
ny = nBy .* 1.0e+9;
nz = nBz .* 1.0e+9;
nt = (nx.^2 + ny.^2 + nz.^2).^0.5;
Rx = (Bx - nx).^2 ;
Ry = (By - ny).^2 ;
Rz = (Bz - nz).^2 ;
Rt = (Bt - nt).^2;
nM = [Rx,Ry,Rz,Rt];
RSx = (sum(nM(:,1))/332)^0.5;
RSy = (sum(nM(:,2))/332)^0.5;
RSz = (sum(nM(:,3))/332)^0.5;
RSt = (sum(nM(:,4))/332)^0.5;
RM = [RSx,RSy,RSz,RSt];
RMS(i,:)= RM; % <-- Subscripted assignment dimension mismatch.
end
%%%%%%%%%%%%%%%%%%%%%%%%%%% test %%%%%%%%%%%%%%%%%%%%%%%%%%

Answers (1)

Walter Roberson
Walter Roberson on 1 Feb 2017
You appear to be trying to store 4 columns at a time into an array that has 9999 columns. Remember when you use : as a subscript you are writing over the entire row or column so the length of the data has to match.

2 Comments

i changed them RMS = zeros(9999) to RMS = zeros(332,4)
and
RM = [RSx,RSy,RSz,RSt];
RMS(i,:)= RM
to
RMS(i,1)= RM(1,1);
RMS(i,2)= RM(1,2);
RMS(i,3)= RM(1,3);
RMS(i,4)= RM(1,4);
but i do not understand the reason!!
A(1, :) = B does not mean "store the data from B into row 1 of A, starting from column 1 and going for as many columns as needed according to the size of B"
Instead, A(1,:) means A(1,1:end) which means A(1,1:size(A,2)). In other words it is asking to overwrite all of row 1 of A, and if there is the wrong amount of data available to be written then that is an error.

Sign in to comment.

Categories

Tags

Asked:

on 1 Feb 2017

Commented:

on 1 Feb 2017

Community Treasure Hunt

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

Start Hunting!