Create FOR loop to insert the matrix elements row-wise
22 次查看(过去 30 天)
显示 更早的评论
I want to create a matrix in an equivalent way as it is possible in C++: just to insert the elements one after the other with a loop like:
cout<<"\nEnter elem. of aug. matrix row-wise:\n";
for (i=1;i<=n;i++) {
for (j=1;j<=n+1;j++) {
cin>>a[i][j]; //input the elements of array
}
}
It is possible to make this in MAtlab ? Something like below, but without to press enter after each element:
% lets say, A=[1 2 ; 5 7 ] but I want just to write only 1 2 5 7 and press ENTER.
n=input('matrix dimension:')
for i=1:n
for j=1:n
a(i,j)=input(' Insert the elements row wise, one after the other:')
end
end
a=reshape(a,n,n)
0 个评论
回答(3 个)
KSSV
2020-8-16
编辑:KSSV
2020-8-16
n=input('number of elements = ') % n = 4
for i=1:n;
a(i)=input('elements-'); % 1 2 5 7
end
a=reshape(a,n/2,n/2)' % not should be even for this example
2 个评论
KSSV
2020-8-16
How about this? When elements is prompted, you enter [1 2 5 7]. Type your values in square brackets.
n=input('number of elements = ') % n = 4
a = input('elements-'); % [ 1 2 5 7]
a=reshape(a,n/2,n/2)' % not should be even for this example
Walter Roberson
2020-8-16
% lets say, A=[1 2 ; 5 7 ] but I want just to write only 1 2 5 7 and press ENTER.
n = input('matrix dimension:')
for i=1:n
s = input( sprintf('Insert the elements for row #%d, all on one row: ', i), 's');
a(i,:) = str2double(strsplit("[" + s + "]"));
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!