Filter löschen
Filter löschen

a function generating a square matrix

58 Ansichten (letzte 30 Tage)
Thomas Kozinski
Thomas Kozinski am 11 Mär. 2021
Beantwortet: Jan am 13 Mär. 2021
Hello!
I am trying to create a function who creating a matrix like that
A = [11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]
And I have no idea how to do it, can someone could give me any tips?
How should I approach that?
Thank you!

Akzeptierte Antwort

Jan
Jan am 13 Mär. 2021
This is not a matrix in Matlab, but invalid syntax:
A = [11 12 13 14]
[21 22 23 24]
[31 32 33 34]
[41 42 43 44]
Do you mean:
A = [11 12 13 14; ...
21 22 23 24; ...
31 32 33 34; ...
41 42 43 44];
Now this is the solution already. You can insert it in a function an in a (useless) loop also:
function A = myFunction
for k = 1:1
A = [11 12 13 14; ...
21 22 23 24; ...
31 32 33 34; ...
41 42 43 44];
end
end
Do you see the problem? he question looks like a homework. With the instructions you have provided, this assignment is meaningless. Most likely you are wanted to create a tiny code to get familiar with Matlab. Then asking for a solution will not help you to learn programming in Matlab.
I guess, there are some more details in the original homework assigment. Maybe you are wanted to use 2 loops:
function A = myFuntion2(n)
A = zeros(n, n);
for i1 = 1:n
for i2 = 1:n
A(i1, i2) = i1 * 10 + i2;
end
end
end
An experienced Matlab programmer would omit the loops:
function A = myFuntion2(n)
v = 1:n;
A = 10 * v.' + v;
end
Do you learn something with reading my suggestions? Most likely you do. But you do not learn to program by your own. See also: FAQ: How to get help for homework questions.

Weitere Antworten (1)

Jorg Woehl
Jorg Woehl am 11 Mär. 2021
Bearbeitet: Jorg Woehl am 11 Mär. 2021
A = [11, 12, 13, 14; 21, 22, 23, 24; 31, 32, 33, 34; 41, 42, 43, 44]
A comma (optional) starts a new column in a matrix, while a semicolon (required) starts a new row. See Get Started with MATLAB: Matrices and Arrays.
  4 Kommentare
Thomas Kozinski
Thomas Kozinski am 12 Mär. 2021
I need to create a function that generates a square matrix A of given size (using loops and conditional statements).
Jorg Woehl
Jorg Woehl am 12 Mär. 2021
Is there a particular reason that you need to use an (inefficient) loop instead of a simple assignment operation? If your question is related to a class assignment, please tag it as "homework".

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by