Send data from MATLAB to Arduino Uno via serial communication

Hi all, my arduino can receive the data from MATLAB. However, the arduino cannot conserve the received data. Below is my MATLAB and arduino code:

MATLAB:
arduinoCom = serial('COM6','BaudRate',9600);
sendData = 5;
fopen(arduinoCom);
fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino
fscanf(arduinoCom);
fclose(arduinoCom);

Arduino code:
int val;
void setup() {
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 0)
{
val = Serial.read();
}
delay(100);
Serial.println(val);
}

In this case, I send a value "5" from MATLAB to arduino via serial communication. If there is no serial data from MATLAB, the value of "val" variable turn to zero. How I can conserve the "val" variable value until the next input from MATLAB. Thank you

If no serial is available no Serial.read is performed and val ought to stay untouched.

What do I miss?

Hello!

Your question may be quite wide. You´ll need to be more specific.

One thing is to store "5", another thing is to store a small group of numbers (and do something with them) and a third thing is to store a large amount of data.

I suggest you taking a look at this topic that may help you on the first steps:

Serial Input Basics - updated

+1 for Robin2's serial input basics.