이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
How can I add linspace in a For Loop
조회 수: 33 (최근 30일)
이전 댓글 표시
Hello good day, I wish to have a 'for' or 'while' loop which keeps increasing the value of 'x' as the value of 'phi' keeps increasing from 0 - 77.3049 with 100 numbers. I attempted a few times but kept getting errors. Any idea how this can be implemented?
댓글 수: 2
Light
2023년 3월 31일
Sorry, X as the value which changes as the value of phi increases. I just cant figure out how to complete the for or while loop at the bottom.
채택된 답변
Star Strider
2023년 3월 31일
There is not enough information (such as a description of what you want to do).
However one possibility is something like this —
phi = linspace(0, 77.3049, 100);
for k = 1:numel(phi)
x(k) = some_calculation_using(phi(k));
end
.
댓글 수: 42
Light
2023년 3월 31일
Okay thanks very much. I would like to declare phi as 0 to 77.3049 with 100 values.
I would also like to have a variable called X() for each of the 100 values from 0 to 77.3049.
Dyuman Joshi
2023년 3월 31일
@Edson, this is what you are looking for.
I would suggest you to pre-allocate x
phi = linspace(0, 77.3049, 100);
%pre-allocation
x=zeros(size(phi))
for k = 1:numel(phi)
x(k) = some_calculation_using(phi(k));
end
Light
2023년 3월 31일
Okay, thanks very much. Could you explain lines 3 with the zeros function and lines 5 with the (phi(k)); ? I dont fully understand it
Star Strider
2023년 3월 31일
The zeros call creates a consecutive memory range that will store the resutls of the calculation. This speeds up a loop that creates new results about 20% over not prealllocating, due to the increased memory efficiency.
The ‘x(k)’ assignment is just an expression that uses the value of ‘phi(k)’ to create some result using it. It is just there for illustration purposes.
Light
2023년 3월 31일
Okay, thank you, I understand now. I also have another question. I edited the code to have 50 values instead of 100 and I got 50 values for x, y and z. Is there any way to use the formula for l and b to calculate the values (for l and b) and plot the various values received?
Dyuman Joshi
2023년 3월 31일
편집: Dyuman Joshi
2023년 3월 31일
1 - A good practice is to club all the for loop together, as their loop indices are same i.e. 1:numel(phi).
for k=1:numel(phi)
X(k)=%code;
Y(k)=%code;
Z(k)=%code;
end
2 - Use semi-colon, ; at the end of a line to suppress the outputs (such as after X, Y and Z), as I've done above.
Star Strider
2023년 3월 31일
I am not going to type those in, since they should be provided as text, not an image.
That aside, the loops are likely not necessary. Just do something like this —
phi = linspace(0, 77.3049, 100);
x1 = ...;
x3 = ...;
y1 = ...;
y3 = ...;
z1 = ...;
z3 = ...;
X = x1*cos(phi) + x3*sin(phi);
Y = ...;
Z = ...;
b = asin(Z);
l = atan2(Y,X);
That should work, eliminating the loops and the need for preallocation. All of those results should be vectors of the appropriate dimensions. The ‘phi’ vector can be any length that produces the desired results.
.
Light
2023년 3월 31일
@Dyuman Joshi okay I will edit the answers, thanks very much.
@Star Strider Wow okay, I got the same values as if I used the loops as well. Thank you. I used the loops because there were many values for phi.
Light
2023년 3월 31일
Awesome, im still getting adjusted to Matlab but I learnt alot from the replies posted.
Light
2023년 4월 1일
I have another question if its okay? We were given this code to edit to plot the path between two cities using the longitude and latitude values. I edited the code but I still keep getting errors. I dont necessarily want the answer but maybe a guide to properly edit the code?
Star Strider
2023년 4월 1일
Copy that line exactly as written in the instructions. Changing it threw the error.
Light
2023년 4월 1일
I copied it exactly the way it was in the instructions and there still was an error
Star Strider
2023년 4월 1일
No, you didn’t.
The 'XTick' and 'YTick' name-value pairs are on different lines in your code, and not within the parentheses.
Look again!
Light
2023년 4월 1일
Sorry I should have stated, initially I copied the code exactly the way it was in the instructions, then I saw an error and edited the code the way it is now with the 'Xtick' and 'Ytick' in separate lines. But I also got an error after attempting to edit it.
Light
2023년 4월 1일
It stated: "Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters."
I also tried correcting it but there was still an error.
Star Strider
2023년 4월 1일
I only have an image of the file, not the actual text, so I can do nothing with it.
Copy the text and paste it to a Comment here.
Dyuman Joshi
2023년 4월 1일
You need to either write the whole command in the same line or use three dots (..., Ellipsis) called at the end of each line break.
Light
2023년 4월 1일
Okay no problem:
load('topo.mat', 'topo', 'topomap1'); % load earth topography whos topo topomap1; % set coordinates of points Longitude = 0:15:360; Latitude = -72:6:72; % set background parameters contour(0:359, -89:90, topo, [0,0], 'w'); axis equal box on set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', [0:180:360], 'YTick', [-90:90:90]); %set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90]); grid; hold on % wait for more plot commands plot(Longitude, Latitude, 'y.', 'linewidth', 1); % enter plot hold off % no more plot commands to come after this line
Star Strider
2023년 4월 1일
Please use one of the options that saves the code in a readable format. I have no strong desire to format this myuself. I will let you put in the line breaks and any other necesary formatting —
load('topo.mat', 'topo', 'topomap1'); % load earth topography whos topo topomap1; % set coordinates of points Longitude = 0:15:360; Latitude = -72:6:72; % set background parameters contour(0:359, -89:90, topo, [0,0], 'w'); axis equal box on set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', [0:180:360], 'YTick', [-90:90:90]); %set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90]); grid; hold on % wait for more plot commands plot(Longitude, Latitude, 'y.', 'linewidth', 1); % enter plot hold off % no more plot commands to come after this line
.
Light
2023년 4월 1일
Okay, do you mean save it as an m file or just structure it in the comment so it is easier to read?
Light
2023년 4월 1일
편집: Walter Roberson
2023년 4월 1일
Okay
load('topo.mat', 'topo', 'topomap1');
% load earth topography whos topo topomap1; % set coordinates of points
Longitude = 0:15:360; Latitude = -72:6:72;
% set background parameters
contour(0:359, -89:90, topo, [0,0], 'w');
axis equal
box on
set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', [0:180:360], 'YTick', [-90:90:90]);
%set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90]);
grid;
hold on % wait for more plot commands
plot(Longitude, Latitude, 'y.', 'linewidth', 1); % enter plot
hold off % no more plot commands to come after this line
Star Strider
2023년 4월 1일
As posted, it runs without error —
load('topo.mat', 'topo', 'topomap1');
% load earth topography whos topo topomap1; % set coordinates of points
Longitude = 0:15:360; Latitude = -72:6:72;
% set background parameters
contour(0:359, -89:90, topo, [0,0], 'w');
axis equal
box on
set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', [0:180:360], 'YTick', [-90:90:90]);
%set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90]);
grid;
hold on % wait for more plot commands
plot(Longitude, Latitude, 'y.', 'linewidth', 1); % enter plot
hold off % no more plot commands to come after this line
Now, use that with the rest of your code.
.
Light
2023년 4월 1일
Wow, amazing thanks very much. Could I ask what caused the errors? Also in line 8 with with set(gca, 'Color' etc. Is a color supposed to be inputted there?
Star Strider
2023년 4월 1일
My pleasure!
The errors were caused by breaking up that line so that all the name-value pair arguments were not within the argument parentheses of the set call. The original code was, as I mentioned previously, correct. The name-value pair arguments that I saw were all correct, so definitely yes.
Light
2023년 4월 1일
Okay thanks very much, I will. Thank you for all your help. Its just one little error I get whenever I run the code, I dont know why. I didnt make any changes to it.
Star Strider
2023년 4월 1일
You have to use continuation ellipses (...) to continue an expression over more than one line —
set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', ...
[0:180:360], 'YTick', [-90:90:90]);
Testing it —
load('topo.mat', 'topo', 'topomap1');
% load earth topography whos topo topomap1; % set coordinates of points
Longitude = 0:15:360; Latitude = -72:6:72;
% set background parameters
contour(0:359, -89:90, topo, [0,0], 'w');
axis equal
box on
set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90], 'XTick', ...
[0:180:360], 'YTick', [-90:90:90]);
%set(gca, 'Color', [0 0 1], 'XLim', [0 360], 'YLim', [-90 90]);
grid;
hold on % wait for more plot commands
plot(Longitude, Latitude, 'y.', 'linewidth', 1); % enter plot
hold off % no more plot commands to come after this line
.
Light
2023년 4월 1일
Okay so I copied the code and implemented some values but if I wish to have a line shown passing through the different points on the plot, do I have to use the polyfit function?
Star Strider
2023년 4월 1일
I am slightly lost, since I’m not certain what you want to plot.
If you have the (x,y) coordinates of the line (whatever ‘x’ and ‘y’ actually are), just plot them using either the plot or line functions.
I believe the hold function is already implemented in the code you’re using. You will need to put any additional plot calls between the hold on and hold off calls that already exist.
Light
2023년 4월 1일
I would like to plot a path between two cities using longitude and latitude (l and b). In the last image I attached, I plotted l vs b but there is no path or line passing through the datapoints between the two cities. I would like to have a path passing through the datapoints from one city to the next using l and b.
Star Strider
2023년 4월 3일
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Performance에 대해 자세히 알아보기
태그
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)