Arrays of unknown size as input

3 次查看(过去 30 天)
Hello everyone,
I want to have an input of 2 arrays which will either be inputed number by number from the user or as a desired range and step. That means that the array sizes won't be known a priori. Thanks a lot in advance!
For clarification:
  2 个评论
Mohammad Sami
Mohammad Sami 2020-6-1
You have to consider what kind of calculations are you doing on your inputs.
As long as your calculations accept variable length inputs, the dimensions would not matter.
Example if you are doing element wise calculation, the dimensions would not matter.
Destro Katramis
Destro Katramis 2020-6-1
Thanks a lot for your answer Mohammad!
The code is looking like this:
x=1:100;
y=1:200;
n=length(x);
k=length(y);
count=0;
for i=1:n
for j=1:k
c=sqrt(x(i)^2+y(j)^2);
if c==fix(c)
count=count+1;
pyth(1,count)=x(i);
pyth(2,count)=y(j);
end
end
end
And I would like to remove the first two lines and replace them with the inputs of the user (following the procedure as stated above).

请先登录,再进行评论。

回答(1 个)

KSSV
KSSV 2020-6-1
You need not to worry about the dimensions of input. You can do what you wanted without loop. Check the below code.
[X,Y] = meshgrid(x,y) ;
C = sqrt(X.^2+Y.^2) ;
idx = C == fix(C) ;
pyth = [X(idx) Y(idx)] ;
So if your question is to ask, how to initialize an unknown array. You can do the following.
x=1:100;
y=1:200;
n=length(x);
k=length(y);
count=0;
pyth = NaN([],2) ; % as you know there are two columns
for i=1:n
for j=1:k
c=sqrt(x(i)^2+y(j)^2);
if c==fix(c)
count=count+1;
pyth(count,1)=x(i);
pyth(count,2)=y(j);
end
end
end
  2 个评论
Destro Katramis
Destro Katramis 2020-6-1
Thanks a lot for your answer KSSV and cudos for the first part, it reduced the number of lines by a significant amount!
If I understand your suggestion correctly, my question is not about the initialization of the array "pyth" before the loop, but as to how to ask the user for input concerning the arrays "x" and "y" (which can be of any size or entered number by number).
KSSV
KSSV 2020-6-1
Ohh....that is pretty simple. Read about the function input.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by