MATLAB Matlab Linspace Problem: How to Control Ky-Points in Loops | Error Fix

  • Thread starter Thread starter hokhani
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The Matlab program encounters a "Subscripted assignment dimension mismatch" error due to the fixed size of the array 'r' when attempting to assign values from 'ky', which changes size with each iteration of the loop. The error occurs because 'r' is not reallocated to match the dimensions of 'ky', which increases as 'ef' changes. To resolve this, 'r' should be reassigned in each loop iteration to accommodate the varying size of 'ky', specifically by initializing 'r' with the dimensions based on 'ky'. Additionally, the discussion includes a request for guidance on using "CODE" tags for proper formatting, which can be done by enclosing code within the specified tags.
hokhani
Messages
556
Reaction score
17
The following Matlab program

clc
clear all
for ef=1:100
ky=linspace(-ef,ef,ef*2);
for n=1:3
r(n,:)=2*ky;
end
end


encounters this error:

? Subscripted assignment dimension mismatch.

Error in ==> testarrays at 6
r(n,:)=2*ky;


But if I use ky=linspace(-ef,ef); there is no error! why?
In other words, what should I do to control the number of ky-points in each loop?
 
Physics news on Phys.org
Next time, please enclose your code in the proper "CODE" tags:
Code:
clc
clear all
for ef=1:100
ky=linspace(-ef,ef,ef*2);
for n=1:3
    r(n,:)=2*ky;
end
end

I guess you are doing something with r after the inner loop, otherwise your code doesn't make sense.

The problem is that the size of r is set the first time around, and won't adjust as the length of ky increases as ef changes. You need to reassing r to an array of the proper size:
Code:
clc
clear all
for ef=1:100
   ky=linspace(-ef,ef,ef*2);
   r = zeros(3,size(ky,2));
   for n=1:3
      r(n,:)=2*ky;
   end
end
 
  • Like
Likes hokhani
Thank you very much. But I can't understand why I have to reassign the size of r in each loop? Why this problem doesn't happen for ky?
I would be grateful also if you tell me how to write in "CODE" tags.
 
hokhani said:
Thank you very much. But I can't understand why I have to reassign the size of r in each loop? Why this problem doesn't happen for ky?
Because for ky, as for r in my version, the entire variable gets reassigned. When you write r(n, : ), the size of r is fixed: the ":" will be replaced by the indices from 1 to the second dimension of r.

hokhani said:
I would be grateful also if you tell me how to write in "CODE" tags.

Just use
[C O D E]
some code
[/C O D E]
(without the spaces between the letters in CODE).
 

Similar threads

Back
Top