I am trying to make a program to print maximum of 5 numbers using for loop and taking number input from user.
I know I can do it via max command by having a =[1,2,3,4,5]; and max(a);.
But trying out with for loop.
I don't know how to take an array in Scilab (I know their is matrix that we can take but don't know how to take input from user in matrix or in array in Scilab)
`a = [1,2,3,4,5];` //works fine but i want user should input numbers.
I know one way is using
a = input("First number:");
b = input("Second number:"); ... and so on upto fifth number
// i want to make it short like using array in C language
int a[5];
printf("Enter numbers");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
// Here in Scilab i don't know how i write it??
if I use int a[5]; i get error Undefined variable: a --error4
I know i can use mprintf & msscanf but question is i am not able to declare or take array data from user's end.
Please suggest me some way to make this program.
Also how to declare & take matrix data from user and declare & take array data from user.
Comments on your solution
Entering matrices
I think your solution is valid, however it could be frustrating for the user to keep providing entries if you have a lot of entries and you know you mistyped the first.
A nice function to have a look at is x_matrix. It provides an easy interface for editing matrices.
Functions
I also usually really prefer functions, it makes it much easier to reuse your code and validate and test small portions. Naturally in this problem the SciLab provided function max() should be used, but you stated you wanted to use a for loop.
Code example
Taking into account the above statements, here is a small working example. You could expand it to let the user first provide the matrix dimensions.
function maximum = findMax( numbers )
maximum = -1e99;
numberOfNumbers = length( numbers );
for i=1:numberOfNumbers
if( numbers(i) > maximum )
maximum = numbers(i);
end
end
return maximum;
endfunction
[result]=x_matrix("enter a matrix", zeros(5,5) );
foundMaximum = findMax(result);
disp( "Maximum is " + string( foundMaximum ) );
I managed to write this code it work's fine now.
But i want more answers also to learn more ways.
disp("Enter Numbers:"); // Enter first number on console then press enter key then type second number and again press enter to type third ..... so on to fifth.
for i = 1:5
x(i) = input('');
end
maximum = x(1)
for i=1:5
if(x(i)>maximum)then
maximum = x(i)
end
end
disp(maximum, "Maximum Number is");
Is it the correct way to write this program and taking input from user this way ??
Qestions remains How to declare & take matrix data from user and declare & take array data from user.
More Answers Needed.
I had a similar problem and found this nice way from the Scilab Help:
labels=["magnitude";"frequency";"phase "];
[ok,mag,freq,ph]=getvalue("define sine signal",labels,...
list("vec",1,"vec",1,"vec",1),["0.85";"10^2";"%pi/3"])
I liked it because you have labels and get a good overview over your data.
In the example above no for loop is included but lists can be created quite flexible and you can for example create the list in a for loop if you need that kind of pattern.
Related
When I have to display the variable value every n iterations of a for loop I always do something along these lines:
for ii=1:1000
if mod(ii,100)==0
display(num2str(ii))
end
end
I was wondering if there is a way to move the if condition outside the loop in order to speed up the code. Or also if there is something different I could do.
You can use nested loops:
N = 1000;
n = 100;
for ii = n:n:N
for k = ii-n+1:ii-1
thingsToDo(k);
end
disp(ii)
thingsToDo(ii);
end
where thingsToDo() get the relevant counter (if needed). This a little more messy, but can save a lot of if testing.
Unless the number of tested values is much larger than the number of printed values, I would not blame the if-statement. It may not seem this way at first, but printing is indeed a fairly complex task. A variable needs to be converted and sent to an output stream which is then printing in the terminal. In case you need to speed the code up, then reduce the amount of printed data.
Normally Matlab function takes vector inputs as well. This is the case for disp and display and does only take a single function call. Further, conversion to string is unnecessary before printing. Matlab should send the data to some kind of stream anyway (which may indeed take argument of type char but this is not the same char as Matlab uses), so this is probably just a waste of time. In addition to that num2str do a lot of things to ensure typesafe conversion. You already know that display is typesafe, so all these checks are redundant.
Try this instead,
q = (1:1000)'; % assuming q is some real data in your case
disp(q(mod(q,100)==0)) % this requires a single call to disp
I'm having trouble with the syntax in Matlab.
I'm trying to split an audio signal up into different segments (frames).
I would like to return the y-axis values to a matrix (each segment having its own column), and the corresponding time values with each segment having its own row.
I can't even get it to return just one single column and row pair (ie one frame). I just get returned two empty matrices. Here's my code.
function [mFrames, vTimeFrame] = Framing(vSignal,samplingRate,frameLPerc,frameshPerc)
totalTime=size(vSignal,1)/samplingRate
frameLength = totalTime*frameLPerc;
frameShift = totalTime*frameshPerc;
frameNumber =0;
check=frameLPerc;
while check<1
check = check+frameshPerc;
frameNumber=frameNumber+1;
end
start = 1;
% problem part
mFrames = vSignal(round((start:1/samplingRate:frameLength)*samplingRate));
vTimeFrame = round((start:1/samplingRate:frameLength)*samplingRate);
end
In the end I would like to be able to segment my entire signal into mFrames(i) and vTimeFrame(i) with a for-loop, but never mind that I cannot even get my function to return the first one (like I said empty matrix).
I know my segment code should be correct because I've got another script working with the same vSignal (it's a column vector by the way) that works just fine (y==vSignal):
voiced = y(round((1.245:1/Fs:1.608)*Fs));
plot(1.245:1/Fs:1.608,voiced)
I titled this with syntax problems because I'm very new to matlab and am used to Java. It feels very weird not initializing anything, and so I'm unsure whether my code is actually making any sense.
When testing I enter [m1,m2]=Framing(y,16000,0.1,0.05).
I got it.
start was not in the right domain. This is correct:
round((start/samplingRate:1/samplingRate:frameLength)*samplingRate)
When I plot(m2,m1) I now get the correct answer.
I do still have another question though, how can I assign these segments to my matrices?
for i=1:frameNumber
mFrames(:,i) = vSignal(round((start/samplingRate:1/samplingRate:frameLength)*samplingRate));
vTimeFrame(i) = round((start/samplingRate:1/samplingRate:frameLength)*samplingRate);
start=start+frameShift;
frameLength=frameLength+frameShift;
end
I get this error
In an assignment A(I) = B, the number of elements in B and I must be the same.
Like I said I'm trying to get the y-axis numbers in columns next to each other and the x-axis in rows.
I have a decent number of edit boxes in a GUI. The majority of them must take in a single real number. I'd like to return an errordlg if the input is not a single real number.
I've been using str2num with some additional checking like isreal when getting the the string of the edit box. An example is shown below:
total_units_buffer = str2num(get(handles_gui.edit_totalunits,'string'));
% Check if input is number and real
if (~isempty(total_units_buffer) && isreal(total_units_buffer))
% Do stuff
end
Usually, the output is [] when the input is not a number, so I've been using isempty as a test as well. However, I discovered recently that if there's an i in the input, like 10i, it will read the number as an imaginary number, instead of returning []. I also recently discovered if you put a space in the input, like 10 10, then str2num will read it as two numbers, which breaks the logic I have now. Furthermore, NaN will also be read as a number.
Basically, I keep discovering these little things that require me to update my testing for a single real number.
So I was wondering, is there a native function to test whether a string is a single real number in Matlab? Or, conversely, is there a guaranteed logic that absolutely ensures the number will be a single real number?
The following should be enough
str = %// your String
x = str2double(str)
y = isfinite(x) && isreal(x)
you could also consider something like this:
y = ~all(x-real(x))
I just have seen, that both methods fail for an input like str = '5,0'. It would be 50 what is certainly not desired. You could avoid this by adding the line:
str = strrep(str,',','.')
I would like to change values within an dataset using eval. It shlould be in a way thet every second value is changed to the one before.
Short example:
A = magic(6)
ds = mat2dataset(A) % original dataset
ds.A1(2:2:end) = ds.A1(1:2:end) % dataset after change
That's the way I would like to do it. Now I need to use the variables letter and number which are assigned previous in the function.
letter = 'A'
number = '1'
eval([strcat('ds.', letter, number)]) % now gives me all values.
This is exactly the point where I would like to index the (1:2:end) to get just the indexed values.
Does one of you have a good idea how to index within the eval function? I would also prefer other ways of doing it if you have on.
Thanks a lot!
1) Don't use eval to achieve dynamic fieldnames:
h=ds.([letter, number])
2) Double indexing is not possible, you need two lines to achieve it.
h(1:2:end)
I am not a very hardcore coder in MATLAB, i have learned every thing from youtube and books. This might be a very simple question but i do not know what search for answer.
In MATLAB i am trying to do something like this.
>>[a,b,c] = [1,2,3]
and i want output like this.
>> a = 1
b = 2
c = 3
So Bsically question is that : - User will define the matrix of variables([a,b,c]) in staring of code and during process of the code similar matrix will be displayed and as input a matrix will be asked([1,2,3]). I dont know how do this without writing a loop code in which i will take every single variable from variable matrix and save the value in that variable by eval function.
well above written code is wrong and i know, i can do this with "for" loop and "eval" function.
but problem is that no. of variables(a,b,c) will never be constant and i want know if there exist any in built function or method in MATLAB which will work better than a for loop.
As i told earlier i don't know what to search for such a problem and either this is a very common question.
Either way i will be happy if you can at least tell me what to search or redirect me to a related question.
Please do write if you want any more information or for any correction.
Thank you.
The deal function can do this for a fixed number of inputs:
[A,B,C]=deal(1,2,3)
If you don't know how many inputs you will get beforehand, you have to do some fooling around. This is what I've come up with:
V=[1,2,3,4,5,6,7]
if length(V)>1
for i=1:length(V)
S{i}=['A' num2str(i)];
G{i}=['V(' num2str(i) ')'];
end
T=[S{1} ','];
R=[G{1} ','];
for i=2:length(V)-1
T=[T S{i} ','];
R=[R G{i} ','];
end
T=[T S{length(V)}];
R=[R G{length(V)}];
eval(['[' T ']=deal(' R ')'])
else
A1=V
end
But then dealing with A1, ... , An when you don't know how many there are will be a pain!
This is somehow known as "tuple unpacking" (at least it's what I would search in python!). I could find this thread which explains that you could do this in Octave (I checked and it works in Matlab also). You have to transform the vector into a cell array before:
values = num2cell([1,2,3])
[a,b,c] = values{:}