Is there a way to automatically extract the first and last number in a for loop?

1 回表示 (過去 30 日間)
Mo A
Mo A 2021 年 6 月 21 日
編集済み: Mo A 2021 年 6 月 21 日
I'm working on a loop that automatically generates nodes and their coordinates. But I've simplified the code to this so it still works:
fid = fopen('hello.txt','w')
w = 100
h = 100
x1 = 30; y1 = 5;
for i= 1 : y1
y = (i+1)/y1 * h
for j= 1 :x1
sd = i*x1 + j + 1
x = (j+1)/x1 * w
ns= ([sd,x,y,0.0])
fprintf(fid,'%10d,%10f,%10f,%10f\n', ns)
end
end
%First, Last , First
So my question is, is there a way to automatically extract the first and last number in the sd column and place them in a format like: First, Last, First. Even if the numbers assigned to the variables at the top changes?

回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 6 月 21 日
編集済み: KALYAN ACHARJYA 2021 年 6 月 21 日
So my question is, is there a way to automatically extract the first and last number in the sd column and place them-
Just store the sd as array
sd=zeros(1,length(x1));
for
for loop
sd(j)=
end
end
First Array Element
sd(1)
& Last Array Element
sd(end)
Set the format as per the requirements
%[first,last,...]
data=[sd(1),sd(end)]
  1 件のコメント
Mo A
Mo A 2021 年 6 月 21 日
編集済み: Mo A 2021 年 6 月 21 日
Hi Kalyan, thank you for your answer. I've tried running the code with the ones you've provided but its not giving me the exact values for the first and last array element.
w = 100
h = 100
x1 = 30; y1 = 5;
sd =zeros(1,length(x1));
for i= 1 : y1
y = (i+1)/y1 * h
for j= 1 :x1
sd(j) = i*x1 + j + 1
x = (sd(j)+1)/x1 * w
ns= ([sd(j),x,y,0.0])
fprintf(fid,'%10d,%10f,%10f,%10f\n', ns)
end
end
data=[sd(1),sd(end)]
I'm not sure why that is?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by