help with my home work plzzzz
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
4. Generate the matrix X= [-10:10; 1:2:42;-10:3:52], then do the following
- Multiply the elements that have a value less than or equal zero by 4.
- Generate a new Matrix Y that have value 1000 if the value of X is less than or equal zero and zero otherwise.
- Calculate number of 1000 in new matrix
%this is for a
clc
clear all
x=[-10:10;1:2:42;-10:3:52];
[r c]=size(x);
for i=1;r;
for j=1:c;
if x(i,j)<0
x(i,j)=4.*x(i,j);
else
x(i,j)=x(i,j);
end
end
end
x
-40 -36 -32 -28 -24 -20 -16 -12 -8 -4 0 1 2 3 4 5 6 7 8 9 10
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41
-10 -7 -4 -1 2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50
what i am doing wron why the third row do not get Multiply by 4
0 Commenti
Risposte (1)
Geoff Hayes
il 13 Mag 2020
Modificato: Geoff Hayes
il 13 Mag 2020
Bader - look closely at the line
for i=1;r;
You have a semi-colon between the 1 and the r. Replace with a colon and it will work as expected:
for i=1:r
By the way, you can remove the else body as it doesn't add any value (since it is changing the value at the given indices).
8 Commenti
Geoff Hayes
il 13 Mag 2020
Bader - the code looks reasonable though you may want to consider pre-sizing the y array. When you run the code, do you get the expected output?
Steven Lord
il 13 Mag 2020
This works for the x you've been given, but it won't work for all x arrays. Consider this 3-dimensional x array:
x = randn(2, 3, 4);
The y you create will be 2-by-12. See the description of the sz1,sz2, ... szn output arguments on the documentation page for the size function for an explanation.
You could simplify this code in at least two different ways. If your assignment requires you to use a for loop, preallocate y to be an array the same size as x. There's an example on the documentation page for the ones function that shows how to do this. Then loop over the elements in the array (there's a function on this page that will help you count the number of elements) and use linear indexing to address each in turn.
Alternately you can skip for loops entirely by preallocating y exactly as in the previous approach then using logical indexing to change the appropriate elements.
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!